如何在 Angular 2 中使用主机监听器和主机绑定(bind)?
我为主机监听器尝试了如下所示,但它始终显示 Declaration expected
错误。
应用程序组件.ts:
import {Component, EventEmitter, HostListener, Directive} from 'angular2/core';
@Directive({
selector: 'button[counting]'
})
class HostSample {
public click = new EventEmitter();
@HostListener('click', ['$event.target']);
onClickBtn(btn){
alert('host listener');
}
}
@Component({
selector: 'test',
template: '<button counting></button>',
directives: [HostSample]
})
export class AppComponent {
constructor(){
}
}
最佳答案
@HostListener
是回调/事件处理程序方法的装饰器,因此删除此行末尾的 ;
:
@HostListener('click', ['$event.target']);
这是一个有效的 plunker我通过复制 API docs 中的代码生成的, 但为了清楚起见,我将 onClick()
方法放在同一行:
import {Component, HostListener, Directive} from 'angular2/core';
@Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
@HostListener('click', ['$event.target']) onClick(btn) {
console.log("button", btn, "number of clicks:", this.numberOfClicks++);
}
}
@Component({
selector: 'my-app',
template: `<button counting>Increment</button>`,
directives: [CountClicks]
})
export class AppComponent {
constructor() { console.clear(); }
}
主机绑定(bind)也可以用来监听全局事件:
To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }
关于angular - 主机绑定(bind)和主机监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34719324/