在结构指令中使用HostListener

Ofe*_*man 6 angular2-directives angular

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

@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();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

和模板:

<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>
Run Code Online (Sandbox Code Playgroud)

还有一个小例子

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

yur*_*zui 5

@HostListener 可以,但是它用于注释html标签,例如:

<!--template bindings={
  "ng-reflect-my-unless": "true"
}-->
Run Code Online (Sandbox Code Playgroud)

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

<!--template bindings={
  "ng-reflect-my-unless": "true"
}-->
Run Code Online (Sandbox Code Playgroud)

柱塞

  • 您可以从刚创建的EmbeddedView中获取`el`:`var el = this.viewContainer.createEmbeddedView(this.templateRef).rootNodes [0];` (2认同)