angular - 当只有一个条件为真时,两个 mat-error 都显示

标签 angular typescript angular-material

当只有一个错误出现时,两个 mat-error 都会显示。

我正在尝试使用 mat-error 制作自定义验证器。当 hasError('') 的值为真时,电子邮件和确认密码的输入均为红色。

我认为我的 MyErrorStateMatcher 类逻辑有问题。请帮忙!我已经尽我所能。提前致谢!

Image

如图所示。当 confirmPassword 抛出错误时,email 字段也是红色的。


我的错误状态匹配器:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control && control.invalid && (control.dirty || control.touched));
    const invalidParent = !!(control && (control.parent.hasError('notTheSame') || control.parent.hasError('emailUsed')));

    return ((invalidCtrl || invalidParent));
  }
}

HTML:(关注邮箱和确认密码)

<form [formGroup]="signupForm" (ngSubmit)="signup(signupForm)">
        <mat-form-field style="width: 100%;">
          <input matInput formControlName="email" placeholder="Email address" type="email" [errorStateMatcher]="matcher" required>
          <mat-error *ngIf="signupForm.controls.email.hasError('required')">Email required!</mat-error>
          <mat-error *ngIf="signupForm.controls.email.hasError('email')">Email invalid!</mat-error>
          <mat-error *ngIf="signupForm.hasError('emailUsed')">This email already exists!</mat-error>
        </mat-form-field>
        <mat-form-field style="width: 100%;">
          <input matInput formControlName="username" placeholder="User name" (blur)="signupForm.value.username != null ? isValidUsername(signupForm.value.username) : ''" required />
          <mat-error>Please enter your new username!</mat-error>
          <mat-error *ngIf="usernameInvalid">Username already exists!</mat-error>
        </mat-form-field>
        <mat-form-field style="width: 100%;">
          <input matInput formControlName="password" placeholder="New password" [type]="show ? 'text' : 'password'" required />
          <mat-icon matSuffix (click)="show = !show" style="cursor: pointer;">{{show ? 'visibility' : 'visibility_off'}}</mat-icon>
          <mat-error>Please enter your password!</mat-error>
        </mat-form-field>
        <mat-form-field style="width: 100%;">
          <input matInput formControlName="confirmPassword" placeholder="Confirm password" type="password" [errorStateMatcher]="matcher" required>
          <mat-error *ngIf="signupForm.controls.confirmPassword.hasError('required')">Please confirm your password!</mat-error>
          <mat-error *ngIf="signupForm.hasError('notTheSame') && signupForm.value.confirmPassword != ''">Password is not the same!</mat-error>
        </mat-form-field>
        <br>
      <button mat-raised-button class="sessionBtn" color="primary" [disabled]="signupForm.invalid">Submit!</button>
</form>

TS:

signupForm = new FormGroup({
    firstName: new FormControl(),
    lastName: new FormControl(),
    email: new FormControl('', [
      Validators.required,
      Validators.email
    ]),
    username: new FormControl(),
    password: new FormControl('', [
      Validators.required
    ]),
    confirmPassword: new FormControl('', [
      Validators.required
    ])
  }, { validators: [this.checkPassword, this.checkExistingEmail] });
  matcher = new MyErrorStateMatcher();

/////////Custom validator////////

  checkPassword(signupForm: FormGroup) {
    let password = signupForm.value.password;
    let confirmPassword = signupForm.value.confirmPassword;

    return password === confirmPassword ? null : { notTheSame: true };
  }

  checkExistingEmail(signupForm: FormGroup) {
    let inputEmail = signupForm.value.email;
    let dbEmail = "test@test.com";

    return inputEmail !== dbEmail ? null: { emailUsed: true };
  }

输入email 和输入confirmPassword 时发生错误,均有[errorStateMatcher]="matcher"

最佳答案

创建自定义错误匹配器

好吧,如果我们想在 <mat-form-field> 中显示错误当input 有效,我们使用 customErrorMatcher。

这是一个类

class CrossFieldErrorMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    //when we want to show the error
    return true 
    //when we want not show the error
    return false
  }
}

通常我们的组件中有

  errorMatcher=new CrossFieldErrorMatcher()
  //and the .html
  <mat-form-field>
    <input matInput formControlName='verifyPassword' 
        [errorStateMatcher]="errorMatcher">
    <mat-error *ngIf="....">
      Passwords do not match!
    </mat-error>
  </mat-form-field>

好吧,我们稍微改变一下,在我们的 customErrorMatcher 中添加一个构造函数

class CrossFieldErrorMatcher implements ErrorStateMatcher {
  constructor(private name:string){}  //<--add a constructor
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    //when we want to show the error, but we can use "name"
    return true 
    //when we want not show the error
    return false
  }
}

然后,我们的组件就变成了

  errorMatcher(name:string)
  {
    return new CrossFieldErrorMatcher(name);
  }

  //and the .html
  <mat-form-field>
    <input matInput formControlName='verifyPassword' 
        [errorStateMatcher]="errorMatcher('password')">
    <mat-error *ngIf="....">
      Passwords do not match!
    </mat-error>
  </mat-form-field>

关于angular - 当只有一个条件为真时,两个 mat-error 都显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56876119/

相关文章:

html - Angular 5 FormGroup 重置不会重置验证器

javascript - Angular 4 : How to show Re-login Dialog/Modal from intercepter

css - 在 Angular 应用程序的按钮中放置链接文本

visual-studio - Typescript:生成的 javascript 文件在 Visual Studio 中不可见

angular - 在 Angular 2.0 中使用 React 的 Material-UI 库

typescript - Angular 2组件未显示

angular - 如何在不重叠的情况下显示多个 snackbar

javascript - 测试 Angular 可观察对象是否发出值或序列

angular - 相对路径。 baseUrl 和路径不适用于 ionic2 - angular2

css - 如何修改angular material主题主色