如何在angular 2中使用主机监听器和主机绑定?我尝试了下面的主机监听器,但它总是显示Declaration expected错误。
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(){
}
}发布于 2016-01-12 11:04:07
@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) { ... }发布于 2017-02-01 08:13:54
下面是使用这两种方法的简单示例:
import {
Directive, HostListener, HostBinding
}
from '@angular/core';
@Directive({
selector: '[Highlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') mouseover() {
this.backgroundColor = 'green';
};
@HostListener('mouseleave') mouseleave() {
this.backgroundColor = 'white';
}
@HostBinding('style.backgroundColor') get setColor() {
return this.backgroundColor;
};
private backgroundColor = 'white';
constructor() {}
}简介:
一些文本背景颜色所以根据调试,我们可以发现这个div已经被
:白色”
一些文本
mouseenter和mouseleave。因此,当我们将鼠标移到div中时,颜色将变为绿色,鼠标离开时,颜色将变为白色。https://stackoverflow.com/questions/34719324
复制相似问题