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

栏目: JavaScript · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/34719324/angular-2-host-binding-and-host-listening

如何使用主机侦听器和主机绑定在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, 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(); }
}

主机绑定也可以用来监听全局事件. “要听全球事件,必须在事件名称中添加一个目标,目标可以是窗口,文档或正文”( reference ):

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

http://stackoverflow.com/questions/34719324/angular-2-host-binding-and-host-listening


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Verilog数字系统设计教程

Verilog数字系统设计教程

夏宇闻 / 北京航空航天大学出版社 / 2003-7-1 / 38.0

《Verilog数字系统设计教程》可作为电子工程类、自动控制类、计算机类的大学本科高年级及研究生教学用书,亦可供其他工程人员自学与参考。一起来看看 《Verilog数字系统设计教程》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具