主机绑定和主机监听

Bha*_*ani 37 angular

如何在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(){
   }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 76

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

@HostListener('click', ['$event.target']);
Run Code Online (Sandbox Code Playgroud)

这是我通过复制API文档中的代码生成的一个有效的plunker,但为了清楚起见,我将该方法放在同一行: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(); }
}
Run Code Online (Sandbox Code Playgroud)

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

要侦听全局事件,必须将目标添加到事件名称.目标可以是窗口,文档或正文(参考)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }
Run Code Online (Sandbox Code Playgroud)


Xin*_*eng 17

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

从'@ angular/core'导入{Directive,HostListener,HostBinding};

@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() {}

}
Run Code Online (Sandbox Code Playgroud)

介绍:

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

    一些文字
  4. 所以根据调试,我们可以发现这个div已被绑定样式="background-color:white"

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