这似乎是一个已知问题。根据this https://github.com/angular/material2/issues/4190#issuecomment-305222426错误状态计算如下:
isInvalid && (isTouched || isSubmitted)
因此,当您提交表格后,isSubmitted
标志设置为true
,因此满足条件并且您的字段显示为红色。有一些解决方法,如果您要重置整个表单,您可以使用resetForm
相反,但在这里您只想重置一个字段,所以......
有一个建议 https://github.com/angular/material2/issues/7522#issuecomment-334478881 to use ErrorStateMatcher https://material.angular.io/components/input/overview#changing-when-error-messages-are-shown:
<input matInput
[placeholder]="'Password'"
ngModel type="password"
name="password" required
[errorStateMatcher]="matcher">
错误状态匹配器:
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
// show errors when touched and invalid
return (control.invalid && control.touched);
}
}
并在你的 TS 中声明一个 ErrorStateMatcher:
matcher = new MyErrorStateMatcher();
似乎有效:堆栈闪电战 https://stackblitz.com/edit/angular-hbq2uv-qi5pbr?file=app/input-error-state-matcher-example.ts