1 回答
TA贡献1911条经验 获得超7个赞
您可以实现ControlValueAccessor,但可能不想重新实现本机输入的方法。为此,您可以使用FormControlDirective来访问 valueAccessor。
formControl并formControlName作为输入属性添加,因此它在这两种情况下都适用。如果formControlName提供,FormControl将从中检索的实例ControlContainer。
@Component({
selector: 'app-custom-input',
template: `<input type="text" [formControl]="control">`,
styleUrls: ['./custom-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomInputComponent,
multi: true
}
]
})
export class CustomInputComponent implements ControlValueAccessor {
@Input() formControl: FormControl;
@Input() formControlName: string;
@ViewChild(FormControlDirective, {static: true})
formControlDirective: FormControlDirective;
private value: string;
private disabled: boolean;
constructor(private controlContainer: ControlContainer) {
}
get control() {
return this.formControl || this.controlContainer.control.get(this.formControlName);
}
registerOnTouched(fn: any): void {
this.formControlDirective.valueAccessor.registerOnTouched(fn);
}
registerOnChange(fn: any): void {
this.formControlDirective.valueAccessor.registerOnChange(fn);
}
writeValue(obj: any): void {
this.formControlDirective.valueAccessor.writeValue(obj);
}
}
来源:https ://medium.com/angular-in-depth/dont-reinvent-the-wheel-when-implementing-controlvalueaccessor-a0ed4ad0fafd
添加回答
举报