Skip to content

Instantly share code, notes, and snippets.

@zekroTJA
Created November 26, 2019 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zekroTJA/d5a55ef656321b18ef7aa82c113e9429 to your computer and use it in GitHub Desktop.
Save zekroTJA/d5a55ef656321b18ef7aa82c113e9429 to your computer and use it in GitHub Desktop.
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