【问题标题】:Angular 7 & Angular Material - Validator not showing MinLength errorAngular 7 & Angular Material - 验证器未显示 MinLength 错误
【发布时间】:2019-03-28 21:26:56
【问题描述】:

我正在使用 Angular 7 和 Angular Material,但我的代码存在一个我无法解决的小问题。如果有的话,下一段代码应该返回一个带有我的消息错误的字符串:

    getPasswordErrorMessage() {
        return this.passwordFormControl.hasError('required') ? 'Password is required' :
              this.passwordFormControl.hasError('minLength') ? 'Password must be at least 6 characters long' : '';
    }

它应该显示在mat-error标签之间:

    <mat-form-field>
        <input matInput minlenght="6" type="password" placeholder="Password" [formControl]="passwordFormControl" [errorStateMatcher]="matcher">
        <mat-error *ngIf="passwordFormControl.invalid">
             {{ getPasswordErrorMessage() }}
        </mat-error>
    </mat-form-field>

无论哪种方式,只会显示“必填字段”错误。不显示minLength错误是否有原因?

【问题讨论】:

    标签: angular angular-material angular-forms


    【解决方案1】:

    这是因为您如何设置返回错误的功能。三元组将返回第一个匹配项,不关心下一个匹配项。

    getPasswordErrorMessage() {
       let error = '';
       error = this.passwordFormControl.hasError('required') ? 'Password is required' : '';
       error = this.passwordFormControl.hasError('minLength') && error ? `${error}   * 
      Password must be at least 6 characters long` : this.passwordFormControl.hasError('minLength') ? 'Password must be at least 6 characters long' : ''; 
     return error;
      }
    

    这应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 2018-09-22
      • 2019-12-10
      • 2018-02-20
      • 1970-01-01
      • 2019-02-06
      • 2016-10-27
      • 1970-01-01
      相关资源
      最近更新 更多