Working with angular 7 and Bootstrap 4, I want to wrap my bootstrap 4 inputs in a custom component in order to reduce the boilerplate in my templates.
I want that the fi
You can implement by implementing ControlValueAccessor
. Lets do the step by step process by building a TextBoxComponent
.
step 1: Creating NG_VALUE_ACCESSOR
for textfield as TEXTBOX_VALUE_ACCESSOR
.
const TEXTBOX_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TextBoxComponent),
multi: true,
};
step 2: implemnting ControlValueAccessor
to our component TextBoxComponent
.
export class TextBoxComponent implements ControlValueAccessor{
...
...
}
step 3: define unimplemnted methods of ControlValueAccessor
. The detailed code of TextBoxComponent
as below.
@Component({
selector: "text-box",
template: `
`,
providers: [TEXTBOX_VALUE_ACCESSOR],
})
export class TextBoxComponent implements ControlValueAccessor {
private _inputValue: any = '';
private _onTouchedCallback: () => {};
private _onChangeCallback: (_:any) => {};
@Input("label") label: string = "Your Label";
@Input("placeholder") placeholder: string = "Your Placeholder";
get inputValue(): any {
return this._inputValue;
}
set inputValue(value: any) {
if (value !== this._inputValue) {
this._inputValue = value;
this._onChangeCallback(value);
}
this._onTouchedCallback();
}
//From ControlValueAccessor interface
writeValue(value: any) {
this._inputValue = value;
}
//From ControlValueAccessor interface
registerOnChange(fn: any) {
this._onChangeCallback = fn;
}
//From ControlValueAccessor interface
registerOnTouched(fn: any) {
this._onTouchedCallback = fn;
}
}
How to use :
The complete code is available in stackblitz.