我需要将一些芯片+自动完成+过滤逻辑封装到单独的组件中。为此,我将“包装器”实现为自定义matInput
构造。似乎在例外情况是当控件进入无效+触摸状态时mat-error
不显示。控件本身显示为无效(红色下划线),但是直到我再次集中控制时,错误消息才会显示。我想念什么?
https://stackblitz.com/edit/angular-w24ch3?file=src%2Fapp%2Fcustominput%2Fcustominput.component.html
相关代码:
import { Component, OnInit, ViewChild } from "@angular/core";
import { FormControl, NgControl } from "@angular/forms";
import { MatFormFieldControl } from "@angular/material/form-field";
import { Observable } from "rxjs";
@Component({
selector: "app-custominput",
templateUrl: "./custominput.component.html",
styleUrls: ["./custominput.component.css"],
providers: [
{provide: MatFormFieldControl, useExisting: CustominputComponent}
]
})
export class CustominputComponent implements OnInit, MatFormFieldControl<any> {
@ViewChild("filterInput", { read: MatFormFieldControl })
matFormFieldControlFilter: MatFormFieldControl<any>;
bizControl = new FormControl(); //tis comes from outside and contains biz value
filterContror = new FormControl(); //this works only as filter for autocomplete (not included here)
constructor() {
this.bizControl.setErrors({ invalid: "artificial-invalid-state" });
}
value = () => this.bizControl.value;
get stateChanges() {
return this.bizControl.statusChanges;
}
get id() {
return this.matFormFieldControlFilter.id;
}
get placeholder() {
return this.matFormFieldControlFilter?.placeholder;
}
ngControl: null;
get focused() {
return this.matFormFieldControlFilter?.focused || false;
}
get empty() {
return !this.bizControl.value;
}
get shouldLabelFloat() {
return this.matFormFieldControlFilter?.shouldLabelFloat;
}
get required() {
return this.matFormFieldControlFilter?.required;
}
get disabled() {
return this.bizControl.disabled;
}
//when fitler is tocuhed, its like touching original controll
get errorState() {
console.log("error state",this.bizControl.invalid && this.filterContror.touched);
return this.bizControl.invalid && this.filterContror.touched;
}
get controlType() {
return this.matFormFieldControlFilter?.controlType;
}
get autofilled() {
return false;//this.matFormFieldControlFilter?.autofilled;
}
get userAriaDescribedBy() {
return this.matFormFieldControlFilter?.userAriaDescribedBy;
}
setDescribedByIds(ids: string[]): void {
this.matFormFieldControlFilter?.setDescribedByIds(ids);
}
onContainerClick(event: MouseEvent): void {
this.matFormFieldControlFilter.onContainerClick(event);
}
ngOnInit() {}
}
自定义输入模板
<p>
<input matInput #filterInput [formControl]="filterContror" />
</p>
父模板
<div [formGroup]="form">
<mat-form-field appearance="legacy">
<app-custominput></app-custominput>
<mat-error>IN ERROR STATE</mat-error>
</mat-form-field>
</div>