Last active
March 25, 2018 12:36
-
-
Save vadimkorr/5edaa4389deb8c2763f7f45a7d374619 to your computer and use it in GitHub Desktop.
ControlValueAccessor implementation
This file contains hidden or 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
| import { Component, Input, ViewChild, ElementRef, Renderer2, forwardRef } from '@angular/core'; | |
| import { ControlValueAccessor } from '@angular/forms'; | |
| @Component({ | |
| selector: 'custom-input', | |
| templateUrl: './input.component.html', | |
| styleUrls: ['./input.component.css'] | |
| }) | |
| export class InputComponent implements ControlValueAccessor { | |
| constructor( | |
| private _renderer: Renderer2 | |
| ) { } | |
| value: string = ''; | |
| @Input() type: string = 'text'; | |
| @Input() id: string; | |
| @Input() placeholder: string = ''; | |
| @ViewChild('inputElement') private _inputElement: ElementRef; | |
| get inputElement(): ElementRef { | |
| return this._inputElement; | |
| } | |
| private _onChange = (_: any) => {}; | |
| private _onTouched = () => {}; | |
| writeValue(obj: any): void { | |
| this.value = obj; | |
| } | |
| registerOnChange(fn: any): void { | |
| this._onChange = fn; | |
| } | |
| registerOnTouched(fn: any): void { | |
| this._onTouched = fn; | |
| } | |
| setDisabledState?(isDisabled: boolean): void { | |
| this._renderer.setProperty(this._inputElement.nativeElement, 'disabled', isDisabled); | |
| } | |
| onChange(event: any) { | |
| this._onChange(event.target.value); | |
| } | |
| onKeyup(event: any) { | |
| this._onChange(event.target.value); | |
| } | |
| onBlur(event: any) { | |
| this._onTouched(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment