当我这样说:
<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中......)
而且,当我把它(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在开始时显示无效:
我能做什么?提前致谢。
只有通过表单字段控件验证失败才能看到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()
}