0 day streak
javascript / expert
Snippet

Custom Control Value Accessor for Reusable UI

Implementing ControlValueAccessor (CVA) allows custom components to integrate seamlessly with Angular's Reactive and Template-driven forms. By providing the NG_VALUE_ACCESSOR token, the component becomes compatible with directives like ngModel or formControlName, bridging the gap between the internal state and the Form API.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Component({
selector: 'custom-input',
template: `<input (input)="onInput($event)" (blur)="onTouched()" [value]="value">`,
providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: CustomInput, multi: true }]
})
export class CustomInput implements ControlValueAccessor {
value: string = '';
onChange = (val: any) => {};
onTouched = () => {};
writeValue(val: string): void { this.value = val; }
registerOnChange(fn: any): void { this.onChange = fn; }
registerOnTouched(fn: any): void { this.onTouched = fn; }
onInput(e: Event) {
this.value = (e.target as HTMLInputElement).value;
this.onChange(this.value);
}
}
angular
Breakdown
1
providers: [{ provide: NG_VALUE_ACCESSOR, ... }]
Registers the component as a valid form control provider.
2
writeValue(val: string)
Used by the forms API to update the component's internal value.
3
registerOnChange(fn: any)
Captures the callback function to notify the form API of value changes.