Angular 4 HostListener & HostBinding

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: `
    
  ` }) 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: `
    

点击该区域,元素会被高亮。点击其它区域,元素会取消高亮

` }) export class AppComponent {}

你可能感兴趣的:(Angular 4 HostListener & HostBinding)