首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >当只有一个条件为真时,两个mat错误都会显示。

当只有一个条件为真时,两个mat错误都会显示。
EN

Stack Overflow用户
提问于 2019-07-03 18:34:01
回答 2查看 4K关注 0票数 2

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

我正在尝试使用mat错误来定制验证器。当电子邮件和确认密码的真实值为hasError(‘)时,它们都是红色的。

我认为我的MyErrorStateMatcher类逻辑是错误的。请帮帮我!我已经尽我所能了。提前谢谢你!

图像

就像你在图像中看到的。当confirmPassword抛出错误时,电子邮件字段也是红色的。

我的ErrorStateMatcher:

代码语言:javascript
代码运行次数:0
运行
复制
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:(关注电子邮件和confimPassword)

代码语言:javascript
代码运行次数:0
运行
复制
<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:

代码语言:javascript
代码运行次数:0
运行
复制
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 };
  }

错误发生在输入电子邮件和输入confirmPassword,两者都有[errorStateMatcher]="matcher"

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-04 17:34:07

创建customErrorMatcher

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

这是一个类似于

代码语言:javascript
代码运行次数:0
运行
复制
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
  }
}

正常情况下,我们有我们的组件

代码语言:javascript
代码运行次数:0
运行
复制
  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中添加一个构造函数

代码语言:javascript
代码运行次数:0
运行
复制
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
  }
}

然后,我们的组件变成

代码语言:javascript
代码运行次数:0
运行
复制
  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>
票数 3
EN

Stack Overflow用户

发布于 2019-07-03 20:03:02

email address字段显示一个错误,因为错误状态匹配器检查父--即表单--这是错误的,因为密码字段不匹配。您需要对电子邮件字段和密码字段使用不同的错误状态匹配器,因为条件不同--如果密码字段不匹配,则电子邮件不需要出错。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56876119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档