小编Ofe*_*man的帖子

在结构指令中使用HostListener

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

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

angular2-directives angular

6
推荐指数
1
解决办法
2084
查看次数

标签 统计

angular ×1

angular2-directives ×1