【问题标题】:mat-form-field is red even though there are no errorsmat-form-field 是红色的,即使没有错误
【发布时间】:2019-02-21 04:01:19
【问题描述】:

我有一个mat-form-field,用于确认用户密码:

<mat-form-field>
  <input matInput required placeholder="Gentag password" [type]="hidePassword ? 'password' : 'text'"
    formControlName="confirmPassword" [errorStateMatcher]="passwordMatcher">
  <mat-icon matSuffix (click)="hidePassword = !hidePassword">{{hidePassword ? 'visibility_off' : 'visibility'}}
  </mat-icon>
  <mat-error *ngIf="registerForm.hasError('mismatch') && !registerForm.hasError('required', 'confirmPassword')">De to passwords matcher ikke</mat-error>
  <mat-error *ngIf="registerForm.hasError('required', 'confirmPassword')">Bekræft venligst passwordet</mat-error>
</mat-form-field>

这是我正在使用的errorStateMatcher

class PasswordErrorStateMathcer implements ErrorStateMatcher {
  isErrorState(control: FormControl, form: import("@angular/forms").FormGroupDirective | import("@angular/forms").NgForm): boolean {
    return !!((control && control.touched && control.parent && control.parent.invalid) || (form.submitted));
  }
}

两个mat-errors按预期工作,但是当错误消失时,该字段保持红色,就好像它仍然有错误一样:

在这里你可以看到打印在控制台中的对象,它说它是有效的:

这就是我创建FormGroup的方式:

this.registerForm = this.builder.group({
      firstName: ["", [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      lastName: ["", [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      email: ["", [Validators.required, Validators.pattern("[a-zA-Z0-9]{1,}([._-]?[a-zA-Z0-9]{1,})*@[a-zA-Z]{2,}([.-]{1}[a-zA-Z0-9]{1,})*[.]{1}[a-zA-Z]{2,}"),
      Validators.maxLength(40)]],
      checkboxGroup: new FormGroup({
        adminCheckbox: new FormControl(false),
        proCheckbox: new FormControl(false),
        researcherCheckbox: new FormControl(false),
        datamanagerCheckbox: new FormControl(false),
      }, this.checkboxValidator),
      password: ["", [Validators.minLength(6), Validators.maxLength(20)]],
      confirmPassword: [""]}, { validator: this.confirmPasswordValidator, });
  }

这是我的confirmPasswordValidator

  confirmPasswordValidator(group: FormGroup) {
    let pass = group.controls.password.value;
    let confirmPass = group.controls.confirmPassword.value;

    return pass === confirmPass ? null : { mismatch: true };
  }

为什么它一直是红色的?

【问题讨论】:

  • Stackblitz 示例?

标签: angular forms validation angular-material


【解决方案1】:

ErrorStateMatcher 检查父表单状态,

return !!((control && control.touched && control.parent && control.parent.invalid) || (form.submitted));

确保父表单有效或以其他方式提交。

要在输入有效数据后消除错误,请更改您的 ErrorStateMatcher 函数

 return !!((control && control.touched && control.invalid) || (form.submitted));

【讨论】:

  • 这解决了我的问题,而且很有意义。但是,我知道它检查了父级,而且我很确定我昨天检查了即使在父级有效之后该字段仍然是红色的,但现在情况不再如此......无论如何,谢谢。
猜你喜欢
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2021-01-22
  • 1970-01-01
相关资源
最近更新 更多