我正在使用Angular Forms在Ionic应用程序中使用电子邮件,密码和“条款和条件”复选框来制作简单表单。我的HTML:
<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>
还有一个简单的Angular组件:
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
});
}
}
我的复选框验证出现问题,无法正常运行。现在,我可以不带复选框提交表单。我只需要使其成为必需-与已经起作用的其他表单值相同,我该怎么做?
我设法使用复选框上的自定义验证程序解决了问题:
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;
}
}
现在,该复选框可以正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句