我正在尝试使用<mat-for-field>
和<mat-error>
进行验证。当用户选中输入而不填充时,这可以正常工作。但是,如何在单击按钮时强制显示此错误?我没有使用提交。此外,使用模板驱动的表单。
这是我的代码:
HTML:
<mat-form-field>
<input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
<mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
TS:
dueDateValidator: FormControl = new FormControl('', [Validators.required]);
如果您希望覆盖此行为(例如,一旦无效控件变脏或父表单组无效时显示错误),您可以使用matInput的errorStateMatcher属性。该属性采用ErrorStateMatcher对象的实例。 ErrorStateMatcher必须实现单个方法isErrorState,该方法接受此matInput的FormControl以及父窗体并返回一个布尔值,指示是否应显示错误。 (true表示应该显示它们,false表示它们不应该显示。)
我会创建一个单独的文件,如default.error-matcher.ts
/** Error when invalid control is dirty or touched*/
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.dirty || control.touched));
}
}
然后在TS文件中添加:
matcher = new MyErrorStateMatcher();
然后更改输入以使用匹配器:
<mat-form-field>
<input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required>
<mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
由于您想在按钮点击时显示mat错误,请尝试以下内容:对于Angular 6版本:
1). import below:
import { FormControl, FormBuilder, FormGroup } from '@angular/forms';
2). declare form control in .ts file:
nameControl = new FormControl('');
3). put control in html:
<mat-form-field style="width: 100%" floatPlaceholder="never">
<input matInput placeholder="your placeholder text" [formControl]="nameControl"
required/>
<mat-error *ngIf="nameControl.errors?.required">name is required</mat-error>
</mat-form-field>
3). on button's click:
this.nameControl.markAsTouched();
检查您使用表单控件的方式很重要,第3点的“.markAsTouched()”将显示相应表单控件的mat错误。
这适合我。 :)点击按钮:
this.nameControl.markAsTouched();
基于Kyle Pfromer的帖子,我发现了我的解决方案(同样的问题):
在TS文件中,我在找到无效表单后添加了StateMatcher,例如。
if (this.myFormGroup.invalid) {
this.matcher = new MyErrorStateMatcher();
return;
}
在MyErrorStateMatcher类中,我更改如下:
return !!(control && control.invalid);
我发现Angular Material无法检测到错误令人困惑。
您也可以点击按钮轻松调用AbstractControl.updateValueAndValidity()
功能。这将在相应的ForControl上再次运行验证过程并显示错误(如果有的话)(基于您的验证器)。
所以,在你的例子中:
checkForErrorsOnButtonClick(): void {
dueDateValidator.updateValueAndValidity();
}