在Angular5中工作,尝试实现密码和确认密码的自定义验证器。
这是.html:
<div formGroupName = "passwordG">
<div class="form-group">
<label for="vat">Password</label>
<input type="password" class="form-control" id="vat" formControlName="password" />
</div>
<div class="form-group">
<label for="vat">Confirmation Password</label>
<input type="password" class="form-control" id="vat" formControlName="Confirmationpassword" />
</div>
<div *ngIf="(passwordG.invalid && passwordG.touched)" class="col-sm-3 text-danger">
<ng-container *ngIf="passwordG.errors?.mismatch;
then first else second"> </ng-container>
<ng-template #first>
Password do not match </ng-template>
<ng-template #second>
Password needs to be more than 8 characters
</ng-template>
</div>
</div>
TS:
ngOnInit() {
this.form = this.formBuilder.group({
passwordG: this.formBuilder.group({
password: ['',[Validators.required,Validators.minLength(9)]],
Confirmationpassword : ['',[Validators.required,Validators.minLength(9)]]
}, {validator: passwordMatch})
});
}
在同一个文件中,在这个类中,我有一个函数:
function passwordMatch(control: AbstractControl):{[key: string]: boolean}{
const password = control.get('password');
const Confirmationpassword = control.get('Confirmationpassword');
if( !password || !Confirmationpassword) {
return null; }
if(password.value === Confirmationpassword.value){
return null;
}
return {
mismatch:true
}
}
问题出在.html文件中,我得到这个错误:
ng: Identified 'passwordG' is not definded. The component declaration ,Template variable declaration and element reference do not contain such a member ,
在线:
<div *ngIf="(passwordG.invalid && passwordG.touched)" class="col-sm-3 text-danger">
有什么想法吗?