我想创建一个自定义表单输入,它只是普通输入的包装,并在formControl
无效时显示错误消息。
所以我创建了一个实现ControlValueAccessor
的组件,但现在我想显示错误消息,我意识到我没有FormControl
,因此我需要将其作为@Input()
传递。问题是......如果我可以将FormControl
作为输入传递,为什么首先实现ControlValueAccessor?我很困惑。
HTML
<input
[placeholder]="placeholder"
[type]="type"
[(ngModel)]="value"
(keyup)="onChange()"
(change)="onChange()"
(blur)="onTouched()"
[disabled]="disabled"/>
TS
@Component({
selector: 'input-app',
templateUrl: './input.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputComponent),
multi: true
}
]
})
export class InputComponent implements ControlValueAccessor {
@Input() type = 'text';
@Input() placeholder = 'placeholder';
@Input() errorMsg = '';
value: string;
disabled: boolean;
private onChangeFn;
private onTouchedFn;
writeValue(val: string | number): void {
this.value = val;
}
registerOnChange(fn: any): void {
this.onChangeFn = fn;
}
registerOnTouched(fn: any): void {
this.onTouchedFn = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
onChange(){
this.onChangeFn(this.value);
}
onTouched(){
this.onTouchedFn();
}
}