1. 程式人生 > >angular 事件繫結/屬性繫結 @HostListener ,@HostBinding

angular 事件繫結/屬性繫結 @HostListener ,@HostBinding

在介紹 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';