角色2:主机绑定和主机侦听

前端之家收集整理的这篇文章主要介绍了角色2:主机绑定和主机侦听前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用主机侦听器和主机绑定在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是回调/事件处理程序方法的装饰器,因此删除;在这行结尾:
@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) { ... }
原文链接:https://www.f2er.com/angularjs/143106.html

猜你在找的Angularjs相关文章