2017-09-25 71 views
1

我正在使用Angular Forms製作帶有電子郵件,密碼和複選框的條款&我的Ionic應用程序中的條件。 我的HTML:Ionic中的Angular 2反應形式複選框驗證

<form [formGroup]="registerForm" (ngSubmit)="register()" class="center"> 
    <ion-item class="input-field"> 
    <ion-input type="email" formControlName="email" placeholder="Email"></ion-input> 
    </ion-item> 
    <ion-item class="input-field"> 
    <ion-input type="password" formControlName="password" placeholder="Password" ></ion-input> 
    </ion-item> 
    <ion-item no-lines> 
    <ion-checkbox formControllName="termsAndConditions"></ion-checkbox> 
    <ion-label>Terms and Conditions</ion-label> 
    </ion-item> 
    <button ion-button full type="submit" [disabled]="!registerForm.valid">Register</button> 
</form> 

和一個簡單的角度分量:

export class RegisterComponent { 
    registerForm: FormGroup; 
    email = new FormControl('', [Validators.required, Validators.email]); 
    password = new FormControl('', [Validators.required]); 
    termsAndConditions = new FormControl('', [Validators.required]); 

    constructor(private formBuilder: FormBuilder) { 
    this.registerForm = this.formBuilder.group({ 
     email: this.email, 
     password: this.password, 
     termsAndConditions: this.termsAndConditions 
    }); 
    } 
} 

我有一個複選框,確認一個問題,因爲我認爲它應該不工作。現在我可以在沒有複選框的情況下提交表單。我只需要使其成爲必需 - 與已經工作的其他表單值相同,我該怎麼做?

回答

1

我管理使用上的複選框自定義驗證解決問題的手段:

export class RegisterComponent { 

    registerForm: FormGroup; 
    email = new FormControl('', [Validators.required]); 
    password = new FormControl('', [Validators.required]); 
    termsAndConditions = new FormControl(undefined, [Validators.required]); 

    constructor(private formBuilder: FormBuilder) { 
    this.registerForm = this.formBuilder.group({ 
     'email': this.email, 
     'password': this.password, 
     'termsAndConditions': this.termsAndConditions 
    }, {validator: this.checkCheckbox }); 
    } 
    public checkCheckbox(c: AbstractControl){ 
    if(c.get('termsAndConditions').value == false){ 
    return false; 
    }else return true; 
} 
} 

現在複選框正常工作。

0

我也遇到了你寫的問題。

private policyButtonValue: boolean; 
在html

::

<input type="checkbox" [(ngModel)]="policyButtonValue"> 

如果單獨的綁定布爾變量是我建議在控制接收表單請求在`寄存器()

後寫一些定製的解決方法的邏輯仍然沒有檢查,你可以自己實現錯誤處理。

private register(values: RegisterCredentials) { 
     if(!policyButtonValue){ 
       ... error stuff here 
     } 
     if (this.form.valid) { 
      ... 
     } 
}