【问题标题】:using HostListener in a structural directive在结构指令中使用 HostListener
【发布时间】:2017-01-10 17:16:42
【问题描述】:

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

在指令中使用@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

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    @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

    【讨论】:

    猜你喜欢
    • 2020-08-21
    • 2018-07-03
    • 2017-04-07
    • 2020-01-10
    • 2019-12-16
    • 2017-10-15
    • 2017-01-02
    • 2019-03-28
    • 2018-09-12
    相关资源
    最近更新 更多