更新 Jenson-button-event 找到更好的选择,请参阅SO answer
查看您的代码,我发现您使用 Angular Material 创建自定义 FormControl。那么,使用 Angular 材质时的问题是如何使“错误”出现。
当我们使用<mat-error> 时,如果控件无效,则会出现错误。考虑到我们的自定义表单控制无效,而不是输入材料。如何避免这种不便?
解决方案是使用 CustomFieldErrorMatcher。如果我们可以创建一个 CustomFiledErrorMatcher 来考虑我们 customFormControl 的错误,我们可以做一些类似的事情
class CustomFieldErrorMatcher implements ErrorStateMatcher {
constructor(private customControl: FormControl) { }
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return control.dirty && this.customControl.invalid;
}
}
嗯,只是在ngAfterView中写一些类似
ngAfterViewInit(): void {
const ngControl: NgControl = this.injector.get(NgControl, null);
if (ngControl) {
setTimeout(() => {
this.control = ngControl.control as FormControl;
})
}
}
有功能
errorMatcher() {
return new CustomFieldErrorMatcher(this.control)
}
并创建我们的 custom-formControl.html 之类的
<mat-form-field>
<mat-select [ngModel]="value" (ngModelChange)="value=$event;onChange($event)"
[placeholder]="placeholder" [disabled]="disabled"
[errorStateMatcher]="errorMatcher()">
<mat-option *ngFor="let option of optionList" [value]="option.value">
{{ option.label }}
</mat-option>
</mat-select>
<mat-error *ngIf="control?.hasError('required')">Required</mat-error>
<mat-error *ngIf="control?.hasError('error')">{{control?.errors.error}}</mat-error>
</mat-form-field>
您可以在stackblitz 中看到两种形式,一种使用 customFormControl,另一种使用 clasic 模式