【发布时间】:2018-11-16 02:38:59
【问题描述】:
在 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})
});
}
在同一个文件 .ts 中,这个类我有一个函数:
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">
有什么想法吗?
【问题讨论】:
-
改用
form.controls['passwordG']。 -
感谢您的帮助:),如果您可以将其添加为答案,我可以为您标记:)
-
没问题@dEs12ZER :) 完成!