mat-error 不显示是错误信息?

mat-error doesn't show that it is an error message?

ts
formControl = new FormControl('', [
    Validators.required, Validators.pattern(/^[a-zA-Z_-]$/),
    Validators.minLength(5), Validators.maxLength(32)
  ]);

  errorMessage(): any {
    if (this.formControl.hasError('required')) {
      return 'You must enter a value';
    } else if (this.formControl.hasError('pattern')) {
      return 'Username can only be letters,underscores and horizontal lines';
    }
  }
html
<mat-error>{{errorMessage()}}</mat-error>
  1. this.formControl.hasError('required') 有效
  2. this.formControl.hasError('pattern') 没用

我查了angular-material文档,没找到用法。 为什么会产生这样的结果?

问题出在您提供的模式上。正确的模式应该是 /^[a-zA-Z_-]{5,32}$/。注意图案中的长度。

formControl 代码如下:

  formControl = new FormControl('', [
    Validators.required, 
    Validators.pattern(/^[a-zA-Z_-]{5,32}$/),
    Validators.minLength(5), 
    Validators.maxLength(32)
  ]);

而且你还应该在mat-error上加上一个条件,这样它只在控件无效时才呈现。像这样:

<mat-error *ngIf="formControl.invalid">{{errorMessage()}}</mat-error>

Link 到 Stackblitz Demo.