目标是比较两个密码字段以检查它们是否相同:
<form [ngFormModel]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<ion-label floating>password</ion-label>
<ion-input type="password" [ngFormControl]="password1" id="password1"></ion-input>
<ion-label floating>Repeat password</ion-label>
<ion-input type="password" [ngFormControl]="password2" id="password2"></ion-input>
<div *ngIf="!myForm.valid">
<p *ngIf="myForm.errors.areEqual">
The two passwords do not match
</p>
</div>
<button type="submit" [disabled]="!myForm.valid">Next</button>
</form>
课程设置如下:
export class SignupPage3 {
myForm: ControlGroup;
password1: AbstractControl;
password2: AbstractControl;
constructor(public nav: NavController, fb: FormBuilder,private signupData: SignupDataService) {
this.myForm = fb.group({
'password1': ['', Validators.required],
'password2': ['', Validators.required]
}, {validator: this.areEqual});
this.password1 = this.myForm.controls['password1'];
this.password2 = this.myForm.controls['password2'];
}
areEqual(group: ControlGroup) {
let password1 = group.controls.password1;
let password2 = group.controls.password2;
if (password1.value === password2.value) {
return null;
} else {
return { "areEqual": true};
}
}
}
当加载类时,我收到此错误:
ORIGINAL EXCEPTION: TypeError: Cannot read property 'areEqual' of null
答案 0 :(得分:0)
我会使用Elvis运算符:
<div *ngIf="!myForm.valid">
<p *ngIf="myForm.errors?.areEqual"> <-----
The two passwords do not match
</p>
</div>