angular 事件绑定/属性绑定 @HostListener ,@HostBinding

来源:互联网 发布:泳衣品牌 知乎 编辑:程序博客网 时间:2024/06/11 15:20

在介绍 HostListener 和 HostBinding 属性装饰器之前,我们先来了解一下 host element (宿主元素)。

宿主元素的概念同时适用于指令和组件。对于指令来说,这个概念是相当简单的。应用指令的元素,就是宿主元素。假设我们已声明了一个 HighlightDirective 指令 (selector: '[exeHighlight]'):

<p exeHighlight>   <span>高亮的文本</span></p>

上面 html 代码中,p 元素就是宿主元素。如果该指令应用于自定义组件中如:

<exe-counter exeHighlight>    <span>高亮的文本</span></exe-counter>

此时 exe-counter 自定义元素,就是宿主元素。

HostListener 是属性装饰器,用来为宿主元素添加事件监听。

在 Angular 中,我们可以使用 HostBinding 装饰器,实现元素的属性绑定。

该指令用于演示如何利用 HostListener 装饰器,监听用户的点击事件

  @HostListener('mouseenter') mouseover() {    this.backgroundColor = 'green';  };  @HostListener('mouseleave') mouseleave() {    this.backgroundColor = 'white';  }
  @HostListener('click', ['$event.target']) onClick(btn) {    console.log("button", btn, "number of clicks:", this.numberOfClicks++);  }
  


此外,我们也可以监听宿主元素外,其它对象产生的事件,如 windowdocument 或body

组件中监听全局事件 The target can be window, document or body

@HostListener('document:keyup', ['$event'])handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }-------------------------------------------------------------------------- 
@HostBinding() innerText = 'Hello, Everyone!';
  @HostBinding('attr.role') role = 'button';
  @HostBinding('class.pressed') isPressed: boolean;
@HostBinding('style.backgroundColor') get setColor() { return this.backgroundColor; }; private backgroundColor = 'white';