Skip to content

Instantly share code, notes, and snippets.

@pratheeshrussell
Last active October 30, 2022 08:56
Show Gist options
  • Select an option

  • Save pratheeshrussell/e650e4d7c3c4985ce4ee3ef3a9630798 to your computer and use it in GitHub Desktop.

Select an option

Save pratheeshrussell/e650e4d7c3c4985ce4ee3ef3a9630798 to your computer and use it in GitHub Desktop.
Two angular directives for 2 way binding without ngModel - make sure to declare in app module
// sample usage: https://stackblitz.com/edit/angular-ivy-lvhg5u?file=src%2Fapp%2Ftwo-way-binder.directive.ts
// <input type="text" id="sample" [(appTwoWayBinder)]="name" />
import {
Directive,
EventEmitter,
HostBinding,
HostListener,
Input,
OnChanges,
Output,
SimpleChanges,
} from '@angular/core';
@Directive({
selector: '[appTwoWayBinder]',
})
export class TwoWayBinderDirective implements OnChanges {
@Input('appTwoWayBinder') model: any;
@Output('appTwoWayBinderChange') update = new EventEmitter<any>();
@HostBinding('value') value: string;
constructor() {}
@HostListener('input', ['$event'])
handleInputChange(event) {
this.update.emit(event.target.value);
}
ngOnChanges(changes: SimpleChanges) {
const changedValue = changes['model'];
this.value = changedValue.currentValue;
}
}
// https://stackblitz.com/edit/angular-ivy-lvhg5u?file=src%2Fapp%2Ftwo-way-form-control.directive.ts
// <input type="text" id="sample" appTwoWayInput [(value)]="valueBind" />
import { Directive, EventEmitter, HostListener, Output } from '@angular/core';
@Directive({
selector: '[appTwoWayInput]',
})
export class TwoWayInputDirective {
@Output('valueChange') update = new EventEmitter<any>();
@HostListener('input', ['$event'])
handleInputChange(event) {
this.update.emit(event.target.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment