主机绑定和主机监听 [英] Host binding and Host listening
问题描述
如何在角度2中使用主机侦听器和主机绑定?
我为主机侦听器尝试了以下操作,但始终显示Declaration expected
错误.
How to use the host listener and host binding in angular 2?
I tried like the below for host listener, but it's always showing a Declaration expected
error.
app.component.ts:
app.component.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
is a decorator for the callback/event handler method, so remove the ;
at the end of this line:
@HostListener('click', ['$event.target']);
这是一个有效的 plunker ,它是通过从 API文档,但是我将onClick()
方法放在为了清楚起见,同一行:
Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick()
method on the same line for clarity:
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(); }
}
主机绑定还可以用于侦听全局事件:
Host binding can also be used to listen to global events:
要监听全局事件,必须在事件名称中添加一个目标. 目标可以是窗口,文档或正文(参考)
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) { ... }
这篇关于主机绑定和主机监听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!