How To Neatly Reference Multiple Angular Event Handlers To Html Elements
I am very new to angular2 and i was wondering if there is a shorter way to write the keypress and paste events so that the html code will be more readable (i am using Type Script):
Solution 1:
When HTML template becomes cluttered with Angular logic, this means that logic should be moved to directive/component classes.
In this case this can be a directive:
@Directive({ selector: '[modify]' })
class ModifyDirective {
@Input() modify;
@HostListener('paste', ['$event.target'])
@HostListener('keypress', ['$event.target'])
onModify(e) {
if (this.modify) {
this.modify(e);
}
}
}
Which is used like
<textarea [modify]="c">
Notice that c
is passed to the directive as a callback, this means that a method should be bound to the context in order to keep proper this
.
Post a Comment for "How To Neatly Reference Multiple Angular Event Handlers To Html Elements"