主机绑定和主机监听

时间:2016-01-11 10:35:38

标签: angular

如何在角度2中使用主机侦听器和主机绑定? 我尝试使用下面的主机监听器,但它始终显示Declaration expected错误。

app.component.ts:

import {Component, EventEmitter, HostListener, Directive} from 'angular2/core';

@Directive({
    selector: 'button[counting]'
})

class HostSample {
    public click = new EventEmitter();
    @HostListener('click', ['$event.target']);
    onClickBtn(btn){
        alert('host listener');
    }
}

@Component({
    selector: 'test',
    template: '<button counting></button>',
    directives: [HostSample]
})

export class AppComponent {
   constructor(){
   }
}

2 个答案:

答案 0 :(得分:74)

@HostListener是回调/事件处理程序方法的装饰器,因此请删除此行末尾的;

@HostListener('click', ['$event.target']);

这是我通过复制plunker中的代码生成的API docs,但为了清晰起见,我将onClick()方法放在同一行:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

主机绑定也可用于收听全局事件:

  

要收听全局事件,必须将目标添加到事件名称。   目标可以是窗口,文档或正文(reference

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

答案 1 :(得分:17)

这是使用它们的简单示例:

import {       Directive,HostListener,HostBinding     }     来自'@ angular / core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

简介:

  1. HostListener可以将事件绑定到元素。
  2. HostBinding可以将样式绑定到元素。
  3. 这是指令,所以我们可以将它用于

    一些文字
  4. 因此根据调试,我们可以发现这个div已被绑定 style =“background-color:white”

    一些文字
  5. 我们还可以发现此div的EventListener有两个事件:mouseentermouseleave。因此,当我们将鼠标移动到div中时,颜色将变为绿色,鼠标离开,颜色将变为白色。