需要在自定义控件的代码中实现ControlValueAccessor接口,并在其中包括对isRequired属性的处理。
示例代码:
首先,在自定义控件中导入ControlValueAccessor:
import { Component, OnInit, Input, forwardRef } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
接下来,实现ControlValueAccessor接口:
@Component({ selector: 'app-custom-control', templateUrl: './custom-control.component.html', styleUrls: ['./custom-control.component.css'], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CustomControlComponent), multi: true } ] }) export class CustomControlComponent implements OnInit, ControlValueAccessor {
onChange: any = () => {}; onTouched: any = () => {};
private _value: any; get value(): any { return this._value; } set value(val: any) { this._value = val; this.onChange(val); this.onTouched(); }
writeValue(val: any) { if (val !== undefined) { this._value = val; } }
registerOnChange(fn: any) { this.onChange = fn; }
registerOnTouched(fn: any) { this.onTouched = fn; }
setDisabledState(disabled: boolean) { // implement this method if needed }
}
在自定义控件的HTML模板中,需要设置isRequired属性,并绑定到内部的input元素:
最后,在父组件中使用自定义控件时,绑定isRequired属性: