Skip to content

Instantly share code, notes, and snippets.

@JoshuaRamirez
Created August 2, 2023 22:36
Show Gist options
  • Save JoshuaRamirez/c8ab599fcbf0acd0a33ef06e416cce9c to your computer and use it in GitHub Desktop.
Save JoshuaRamirez/c8ab599fcbf0acd0a33ef06e416cce9c to your computer and use it in GitHub Desktop.
Bind Directive to perform true Two-Way Data-Binding in Angular
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