您可以使用ControlValueAccessor
接口来自定义Angular Material表单字段控件,并在其中访问NgControl
。以下是一个示例解决方案:
首先,创建一个自定义表单字段控件组件,实现ControlValueAccessor
接口:
import { Component, forwardRef, Input, OnInit, Provider } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgControl } from '@angular/forms';
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomFormFieldComponent),
multi: true
};
@Component({
selector: 'app-custom-form-field',
template: `
`,
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomFormFieldComponent implements ControlValueAccessor, OnInit {
@Input() placeholder: string;
@Input() disabled: boolean;
value: any;
onChange: any = () => {};
onTouched: any = () => {};
constructor(private ngControl: NgControl) {}
ngOnInit() {
// 注册控件访问器
this.ngControl.valueAccessor = this;
}
writeValue(value: any) {
this.value = value;
this.onChange(value);
this.onTouched();
}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
}
然后,在使用该自定义表单字段控件的父组件中,您可以通过ViewChild
装饰器访问NgControl
:
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgControl } from '@angular/forms';
import { CustomFormFieldComponent } from './custom-form-field.component';
@Component({
selector: 'app-parent-component',
template: `
`
})
export class ParentComponent implements OnInit {
@ViewChild('customFormField', { static: true }) customFormField: CustomFormFieldComponent;
constructor() {}
ngOnInit() {}
logNgControl() {
console.log(this.customFormField.ngControl);
}
}
在上面的示例中,我们通过ViewChild
装饰器将CustomFormFieldComponent
实例赋值给customFormField
变量,并通过customFormField.ngControl
访问NgControl
实例。
这样,您就可以在自定义表单字段控件中访问NgControl
实例,并执行需要的操作。