Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular Control Value Accessor Component Example
/** @format */
import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
// tslint:disable-next-line: no-use-before-declare
useExisting: forwardRef(() => EntryInputComponent),
multi: true,
};
@Component({
selector: 'app-entryinput',
templateUrl: './entryinput.component.html',
styleUrls: ['./entryinput.component.scss'],
})
export class EntryInputComponent implements ControlValueAccessor {
private _value: string;
private onTouchedCallback: () => void = () => {};
private onChangeCallback: (_: any) => void = () => {};
public get value(): string {
return this._value;
}
public set value(v: string) {
if (v !== this._value) {
this._value = v;
this.onChangeCallback(v);
}
}
public writeValue(v: string) {
if (v !== this._value) {
this._value = v;
}
}
public registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
public registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.