Both mat-error show when only one condition is true

前端 未结 2 1775
栀梦
栀梦 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 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
      
        
        
          Passwords do not match!
        
      
    

    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
      
        
        
          Passwords do not match!
        
      
    

提交回复
热议问题