我有一个自定义表单组件。我在模板驱动的表单上使用我的组件。 我怎么能把我的组件包含到form.controls集合中,类似于输入字段在form.controls中? 我想找到我的组件来判断它是否脏。我的组件包裹了第3个。没有实现ControlValueAccessor的派对UI组件。
const EDITOR_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OptionChoiceComponent),
multi: true
};
@Component({
selector: 'option-choice',
templateUrl: './option-choice.component.html',
styleUrls: ['./option-choice.component.scss'],
providers: [ EDITOR_VALUE_ACCESSOR ]
})
export class OptionChoicer implements OnInit, ControlValueAccessor {
private hasChoice: boolean;
onPropagateChange: Function = () => {};
onModelTouched: Function = () => {};
constructor() { }
get value(): boolean {
this.hasChoice;
}
set value(v: boolean) {
this.hasChoice = v;
}
ngOnInit() {
this.hasChouce = false;
}
onChoiced(event) {
this.onModelTouched(true);
this.onPropagateChange(true);
}
writeValue(value: any): void {
if (value) {
this.hasChoice = value;
}
}
registerOnChange(fn: Function): void {
this.onPropagateChange = fn;
}
registerOnTouched(fn: Function): void {
this.onModelTouched = fn;
}
setDisabledState(val: boolean): void {
}
}
调用我的组件如下:
optionIsChoice is boolean
<option-choice id="optionchoice" [(ngModel)]="optionIsChoice"></option-choice>