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: `
    <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 {}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 14,107评论 6 13
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,288评论 19 139
  • 妈妈,这个词,总是给人温暖,安全感。但妈妈,这个词,也给人无限的压力。成为多宝妈妈两年一个月,虽然也轻微抑郁过,烦...
    菇妈阅读 5,005评论 0 5
  • 昨天看到一个专栏的笔者的简介里写着:还有什么比无趣更可怕? 网友说:无知。我惭愧地低下了头。 于是,我在思考,无趣...
    铛妹阅读 4,021评论 0 0

友情链接更多精彩内容