Angular5自定义验证器:ng:已识别'密码G'没有被定义。

时间:2018-06-06 12:01:02

标签: angular angular5 frontend

使用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">

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

passwordG本身未在组件中定义。

如果要访问表单中的控件,可以使用

form.controls['passwordG']form.get('passwordG')