如何整齐地将多个角度事件处理程序引用到html元素 [英] how to neatly reference multiple angular event handlers to html elements
本文介绍了如何整齐地将多个角度事件处理程序引用到html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对angular2还是很陌生,我想知道是否有较短的方法来编写 keypress
和 paste
事件,以便html代码更具可读性(我正在使用Type Script):
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>
推荐答案
当HTML模板因Angular逻辑变得混乱时,这意味着应将逻辑移至指令/组件类.
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);
}
}
}
使用方式类似于
<textarea [modify]="c">
请注意,将 c
作为回调传递给指令,这意味着应将方法绑定到上下文,以保持正确的 this
.
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
.
这篇关于如何整齐地将多个角度事件处理程序引用到html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文