非常感谢@Eliseo,但该解决方案不适用于我现有的代码(不同的绑定方式,Angular 8?),我变得更加沮丧 - ngControl.control 始终未定义..
该解决方案显然不需要自定义ErrorStateMatcher,但答案是确保mat-select 绑定到FormGroup 中的FormControl,这是由于生命周期事件而繁琐,但有效:
export class DatasetSelectComponent extends AbstractFormFieldComponent {
@Input() label!: string;
@Input() items!: [{id: number, label: string}];
}
export abstract class AbstractFormFieldComponent implements ControlValueAccessor {
// tslint:disable-next-line:variable-name
_formControl = new FormControl();
onChange = (value: any) => {};
constructor(@Self() @Optional() public ngControl: NgControl) {
if(this.ngControl) {
this.ngControl.valueAccessor = this;
}
}
ngAfterViewInit(): void {
if (this.ngControl) {
/**
* get a handle on the FormControl that was created in the last Reactive FormGroup in the component injection hierarchy
* so that it can be bound to the input in our Custom Component
* this ensures input value binding to model + explicit validation is bound
* e.g. new FormGroup({ titleId: new FormControl(personalDetails.titleId, Validators.required) } =>
* <input [formControl]="this.formControl"
* otherwise you will have to do that manually for evey single control on every single form
* which is obviously a lot of repeating yourself
*/
of(this.ngControl.control)
.pipe(
skipWhile(fc => !fc),
take(1)
)
.subscribe(fc => {
this.formControl = fc as FormControl;
console.log(
'Custom FormControl (AbstractFormFieldComponent): Binding to Reactive Form',
this.ngControl,
this.ngControl.control
);
});
}
get formControl() :FormControl|RequiredFormControl {
return this._formControl;
}
set formControl(forControl:FormControl|RequiredFormControl) {
this._formControl = forControl;
}
registerOnChange(fn: (value: any) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: (value: any) => void): void {}
writeValue(value: any): void {
if(this.formControl) this.formControl.setValue(value, { emitEvent: false });
}
}
注意删除NG_VALUE_ACCESSOR的组件注入(由构造函数中的工作替换),这可以防止循环依赖编译时错误:
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => CustomSelectComponent),
}
]
还有来自模板的 sn-p:
<mat-select [formControl]="formControl" [required]="formControl.required">
<mat-option *ngFor="let item of items" [value]="item.id">
{{ item.label }}
</mat-option>
</mat-select>
Updated blitz