Skip to content

Instantly share code, notes, and snippets.

@pratheeshrussell
Created May 27, 2023 12:26
Show Gist options
  • Save pratheeshrussell/e1dad57b643a676d54d8bb10d5939607 to your computer and use it in GitHub Desktop.
Save pratheeshrussell/e1dad57b643a676d54d8bb10d5939607 to your computer and use it in GitHub Desktop.
Two way binder for Angular
import { Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, Output, SimpleChanges } from '@angular/core';
@Directive({
selector: '[appTwoWayBinder]'
})
export class TwoWayBinderDirective {
@Input('appTwoWayBinder') model: any;
@Output('appTwoWayBinderChange') update = new EventEmitter<any>();
@HostBinding('value') value: (string|undefined);
element :any;
constructor(private elementRef: ElementRef) {
this.element = this.elementRef.nativeElement;
}
@HostListener('input', ['$event'])
handleInputChange(event:any) {
let valueToEmit:(string|boolean|number) = event.target.value;
if (this.element instanceof HTMLInputElement) {
if (this.element.type === 'checkbox' || this.element.type === 'radio') {
valueToEmit = event.target.checked;
}
}
this.update.emit(valueToEmit);
}
ngOnChanges(changes: SimpleChanges) {
const changedValue = changes['model'];
if (this.element instanceof HTMLInputElement) {
if (this.element.type === 'checkbox' || this.element.type === 'radio') {
this.element.checked = changedValue.currentValue;
return;
}
}
//
this.value = changedValue.currentValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment