Angular 4 HostListener & Hos
2018-02-26 本文已影响17人
阿踏
HostListener 是属性装饰器,用来为宿主元素添加事件监听。
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: 'button[counting]'
})
class CountClicks {
numberOfClicks = 0; @HostListener('click', ['$event.target'])
onClick(btn: HTMLElement) { console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
}
}
import { Component} from '@angular/core';
@Component({
selector: 'exe-app',
styles: [`
button {
background: blue;
color: white;
border: 1px solid #eee;
}
`],
template: `
<button counting>增加点击次数</button>
` }) export class AppComponent {}
此外,我们也可以监听宿主元素外,其它对象产生的事件,如 window 或 document 对象。具体示例如下:
import { Directive, HostListener, ElementRef, Renderer } from '@angular/core';
@Directive({
selector: '[exeHighlight]'
})
export class ExeHighlight { constructor(private el: ElementRef, private renderer: Renderer) { } @HostListener('document:click', ['$event'])
onClick(btn: Event) { if (this.el.nativeElement.contains(event.target)) { this.highlight('yellow');
} else { this.highlight(null);
}
}
highlight(color: string) { this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
}
}
import { Component} from '@angular/core'; @Component({
selector: 'exe-app',
template: `
<h4 exeHighlight>点击该区域,元素会被高亮。点击其它区域,元素会取消高亮</h4>
` }) export class AppComponent {}