【问题标题】:Angular5 Custom validators : ng: Identified 'passwordG' is not definded.Angular 5 自定义验证器:ng:未定义识别的“密码”。
【发布时间】: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 :) 完成!

标签: angular angular5 frontend


【解决方案1】:

passwordG 本身并没有在组件中定义。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2019-01-07
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多