1 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以實(shí)現(xiàn)ControlValueAccessor,但可能不想重新實(shí)現(xiàn)本機(jī)輸入的方法。為此,您可以使用FormControlDirective來訪問 valueAccessor。
formControl并formControlName作為輸入屬性添加,因此它在這兩種情況下都適用。如果formControlName提供,F(xiàn)ormControl將從中檢索的實(shí)例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
添加回答
舉報(bào)