Reputation: 5986
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):
<textarea rows="1" class="txt" (keypress)="c()" (paste)="c()" [(ngModel)]="LeftText"></textarea>
Upvotes: 1
Views: 2706
Reputation: 222309
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
.
Upvotes: 4