Last active
October 30, 2022 08:56
-
-
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
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
| // 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; | |
| } | |
| } |
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
| // 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