在结构指令中使用HostListener

时间:2016-09-02 14:34:18

标签: angular angular2-directives

我有一个结构指令,需要在主机上监听事件,就像在属性指令上完成一样。

在指令中使用@HostListener没有错误,但没有收到任何事件。

这是指令代码:

import { Directive, HostListener, Input } from '@angular/core';

import { TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[myUnless]' })
export class UnlessDirective {

constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
    ) { }

@HostListener("click", ["$event"]) public onClick(event: any) {
        console.log("click", event);
}

@Input() set myUnless(condition: boolean) {
    if (!condition) {
    this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
    this.viewContainer.clear();
    }
}
}

和模板:

<h1>Structural Directive with HostListener</h1>


<p *myUnless="condition">
condition is false and myUnless is true.
</p>

<p *myUnless="!condition">
condition is true and myUnless is false.
</p>

还有plunker example

问题是,是否可以在结构指令中使用@HostListener

1 个答案:

答案 0 :(得分:4)

@HostListener有效,但它适用于评论html标记,如:

<!--template bindings={
  "ng-reflect-my-unless": "true"
}-->

您可以尝试以下解决方法:

@Directive({ selector: '[myUnless]' })
export class UnlessDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private renderer: Renderer) { }

  onClick(event: any) {
    console.log("click", event);
  }

  @Input() set myUnless(condition: boolean) {
    if (!condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);

      const el = this.templateRef.elementRef.nativeElement.nextElementSibling;
      this.renderer.listen(el, 'click', this.onClick);  
    } else {
      this.viewContainer.clear();
    }
  }
}

Plunker