Created
August 2, 2023 22:36
-
-
Save JoshuaRamirez/c8ab599fcbf0acd0a33ef06e416cce9c to your computer and use it in GitHub Desktop.
Bind Directive to perform true Two-Way Data-Binding in Angular
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
import {Directive, EventEmitter, forwardRef, HostListener, Input, Output} from '@angular/core'; | |
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; | |
@Directive({ | |
selector: '[Bind]', | |
providers: [ | |
{ | |
provide: NG_VALUE_ACCESSOR, | |
useExisting: forwardRef(() => BindDirective), | |
multi: true, | |
}, | |
], | |
}) | |
export class BindDirective implements ControlValueAccessor { | |
@Input('Bind') | |
public value: any; | |
@Output('BindChange') | |
public valueChange: EventEmitter<any> = new EventEmitter(); | |
public onChange: any = () => {}; | |
public onTouched: any = () => {}; | |
public writeValue(value: any): void { | |
this.value = value; | |
} | |
public registerOnChange(fn: any): void { | |
this.onChange = fn; | |
} | |
public registerOnTouched(fn: any): void { | |
this.onTouched = fn; | |
} | |
@HostListener('keyup', ['$event.target.value']) | |
public onInput(value: any) { | |
this.value = value; | |
this.onChange(this.value); | |
this.valueChange.emit(this.value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment