如何使用主机侦听器和主机绑定在angularjs 2?
我尝试这样做主机监听器,但总是显示“声明预期”错误.
我尝试这样做主机监听器,但总是显示“声明预期”错误.
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是回调/事件处理程序方法的装饰器,因此删除;在这行结尾:
原文链接:https://www.f2er.com/angularjs/143106.html@HostListener('click',['$event.target']);
这是通过复制API docs中的代码生成的plunker,但是为了清楚起见,我将onClick()方法放在同一行上:
import {Component,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(); } }
主机绑定也可以用来监听全局事件. “要听全球事件,必须在事件名称中添加一个目标,目标可以是窗口,文档或正文”(reference):
@HostListener('document:keyup',['$event']) handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }