* ngIf =“name.invalid”不适用于Angular Material

问题描述 投票:1回答:1

当我这样说:

<textarea #name="ngModel" class="form-control" id="" cols="30" rows="3" style="resize:none" required></textarea>
<div *ngIf="name.invalid" class="alert alert-danger">
     <div *ngIf="name.errors.required">
            Name is required.
      </div>
</div>

当视图开始时我得到了这个:(没关系,我想要这样的东西但是在Angular Material中......)enter image description here

而且,当我把它(Angular Material):

<mat-form-field>
  <textarea matInput #name="ngModel" class="form-control" id="" cols="30" rows="3" style="resize:none" required></textarea>
  <mat-error *ngIf="name.invalid">Name is required.</mat-error>
</mat-form-field>

我懂了:

它显然是无效的,但没有任何反应,没有红色。当我手动聚焦并模糊textarea时,<mat-error>出现。我希望这个textarea在开始时显示无效:enter image description here

我能做什么?提前致谢。

angular material
1个回答
2
投票

只有通过表单字段控件验证失败才能看到mat-error元素。

Angular材质使用默认的ErrorStateMatcher来检查该控件是否有效:

@Injectable({providedIn: 'root'})
export class ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.touched || (form && form.submitted)));
  }
}

如您所见,只有触摸控件或提交表单才会失败。

您可以通过在控件上使用errorStateMatcher输入来覆盖此行为:

HTML

<textarea matInput ... [errorStateMatcher]="matcher" required></textarea>

TS

import {ErrorStateMatcher} from '@angular/material/core';

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(
       control: FormControl | null,
       form: FormGroupDirective | NgForm | null): boolean {
    return control && control.invalid;
  }
} 

@Component({
  ...
})
export class AppComponent  {

  matcher = new MyErrorStateMatcher()
}

Ng-run Example

© www.soinside.com 2019 - 2024. All rights reserved.