Both mat-error show when only one condition is true

前端 未结 2 1779
栀梦
栀梦 2021-01-16 09:08

Both mat-error show when only one error appeared.

I\'m trying to make custom validators with mat-error. Both input for email and confirm password are red when each

相关标签:
2条回答
  • 2021-01-16 09:46

    Creating a customErrorMatcher

    Well, if we want to show an error in a <mat-form-field> when the input is valid, we use a customErrorMatcher.

    This is a class like

    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
      }
    }
    

    Normally we has in our component

      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>
    

    Well, we are change the things a bit, adding a constructor in our 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
      }
    }
    

    Then, our component becomes

      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>
    
    0 讨论(0)
  • 2021-01-16 09:52

    The email address field shows an error because the error state matcher checks the parent - which is the form - which is in error because the password fields do not match. You need to use different error state matchers for the email field and password fields because the conditions are different - email does not need to be in error if the password fields don't match.

    0 讨论(0)
提交回复
热议问题