主机绑定和主机监听

43

如何在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个回答

85

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

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

这是我生成的一个工作中的plunker,我是通过从API文档中复制代码的方式生成的,但为了更清晰地表达,我将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(); }
}

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

要监听全局事件,必须将目标添加到事件名称中。 目标可以是window、document或body (参考)

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

谢谢Mark。现在我找到了我的错误。我在这一行末尾使用了分号 -> @HostListener('click', ['$event.target']); 这导致了声明预期的错误。 - BhaRathi RajaMani
我正在使用“blur”事件进行此操作,在Chrome中可以正常工作,但在IE 11中无法。 我现在正在使用angular2 beta.8。 来自angular polyfills的错误:EXCEPTION:Error during evaluation of "blur" ORIGINAL EXCEPTION:TypeError:Object doesn't support this action。 如果您以前没有看到过这个问题,我可以开一个新问题,但我很快就需要升级到RC版本。 - ps2goat
Plunker上的示例很好,我理解HostListener修饰符。在组件中只使用(click)= function() ...可以省略此修饰符来进行按钮计数吗?我的意思是,在组件中仅使用(click)= function() ...不比使用该修饰符更清晰吗? - stackdave
你能更新一下链接吗?那个页面已经不存在了。 - Sam
我应该避免使用 directives 属性,否则会出现以下错误: "Object literal may only specify known properties, and 'directives' does not exist in type 'Component'.ts(2345)" 我猜我可以在模块上使用 Declarations 属性? - Nate Anderson
显示剩余2条评论

17

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

import {
  Directive, HostListener, HostBinding
}
from '@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的样式已经绑定了

    样式 = "background-color:white"
    一些文本
  5. 我们还可以发现这个div的EventListener有两个事件:mouseentermouseleave。因此当我们把鼠标移动到div中时,颜色会变成绿色,鼠标离开时,颜色会变成白色。


我们可以解除主机监听器吗? - canbax

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接