Created
November 26, 2019 08:47
-
-
Save zekroTJA/d5a55ef656321b18ef7aa82c113e9429 to your computer and use it in GitHub Desktop.
Angular Control Value Accessor Component Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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