如果你在 Angular 14 中创建了一个自定义表单控件但该控件不能正常渲染,可能是因为你没有正确实现 ControlValueAccessor 接口。以下是一个示例,展示如何正确实现 ControlValueAccessor 接口:
确保你的表单控件实现了 ControlValueAccessor 接口,并在组件的 providers 中注册。
在组件类中实现 ControlValueAccessor 接口:
@Component({ selector: 'app-custom-control', templateUrl: './custom-control.component.html', providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CustomControlComponent), multi: true, }, ], }) export class CustomControlComponent implements ControlValueAccessor { private _value: any; private onChange: (value: any) => void = () => {}; private onTouched: () => void = () => {};
get value(): any { return this._value; }
set value(value: any) { if (value !== this._value) { this._value = value; this.onChange(value); } }
writeValue(value: any): void { this.value = value; }
registerOnChange(fn: (value: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
setDisabledState?(isDisabled: boolean): void { console.log(isDisabled); } }