Sometimes, we want to create a custom form input with Angular.
In this article, we’ll look at how to create a custom form input with Angular.
How to create a custom form input with Angular?
To create a custom form input with Angular, we can create a component that implements the ControlValueAccessor
class.
For instance, we write
import { Component, Provider, forwardRef, Input } from "@angular/core";
import {
ControlValueAccessor,
NG_VALUE_ACCESSOR,
CORE_DIRECTIVES,
} from "@angular/common";
const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(NG_VALUE_ACCESSOR, {
useExisting: forwardRef(() => InputField),
multi: true,
});
@Component({
selector: "inputfield",
template: `<input [(ngModel)]="value" />`,
directives: [CORE_DIRECTIVES],
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR],
})
export class InputField implements ControlValueAccessor {
private _value: any = "";
get value(): any {
return this._value;
}
set value(v: any) {
if (v !== this._value) {
this._value = v;
this.onChange(v);
}
}
writeValue(value: any) {
this._value = value;
this.onChange(value);
}
onChange = (_) => {};
onTouched = () => {};
registerOnChange(fn: (_: any) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
}
to create the InputField
class.
In it, we have a getter and setter to get the set the input value respectively.
In the template, we have an input that binds the input value to the value
variable.
Also, we add the registerOnChange
and registerOnTouched
methods, to add the change and touch event functions.
We also set providers
to [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
so that we can use the component as a custom input that can bind to input values in template and reactive forms.
Conclusion
To create a custom form input with Angular, we can create a component that implements the ControlValueAccessor
class.