角色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('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
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- Vue 计算属性与侦听器
- Vue入门指南——侦听器
- Vue:学习笔记(四)-计算属性和侦听器
- Vue源码学习: 关于对Array的数据侦听
- vue 核心之一 计算属性computed 和侦听属性watch
- ????150行代码带你实现小程序中的数据侦听
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Algorithmic Beauty of Plants
Przemyslaw Prusinkiewicz、Aristid Lindenmayer / Springer / 1996-4-18 / USD 99.00
Now available in an affordable softcover edition, this classic in Springer's acclaimed Virtual Laboratory series is the first comprehensive account of the computer simulation of plant development. 150......一起来看看 《The Algorithmic Beauty of Plants》 这本书的介绍吧!