未收到自定义指令的输出

时间:2017-01-31 12:30:22

标签: angular angular2-directives

我试图从自定义指令接收事件,但它无法正常工作。我的应用程序中有几个成功发送事件的组件,所以我做了一个最小的例子:

<div *appDummyDirective="allTheThings" (dummyOutput)="dummyOuputDirective()">
    appDummyDirective
</div>
<appDummyComponent (dummyOutput)="dummyOuputComponent()"></appDummyComponent>

当指令的回调不是:

时,将调用组件的回调
dummyOuputComponent() {
    console.log('dummyOuputComponent()'); //gets called
}

dummyOuputDirective() {
    console.log('dummyOuputDirective()'); //does not get called!
}

以下是指令和组件的定义。

@Directive({
selector: '[appDummyDirective]'
})

export class DummyDirective{
    @Output() dummyOutput = new EventEmitter<any>();
    @Input() appDummyDirective: any;

    constructor(private viewContainer: ViewContainerRef, private template: TemplateRef<any>) {
        this.viewContainer.createEmbeddedView(this.template);
        setInterval(any => { this.dummyOutput.emit(null); console.log('fire dummy directive'); }, 1000);
    }
}

@Component({
    selector: 'appDummyComponent',
    template: 'appDummyComponent'
})

export class DummyComponent{
    @Output() dummyOutput = new EventEmitter<any>();

    constructor() {
        setInterval(any => { this.dummyOutput.emit(null); console.log('fire dummy component'); }, 1000);
    }
}

我的指令出了什么问题?

1 个答案:

答案 0 :(得分:0)

显然@Output不能使用*的语法糖。

如果您去掉指令并将回调绑定应用于template元素,它就会起作用。

<template [appDummyDirective]="allTheThings" (dummyOutput)="dummyOuputDirective()">
    <div >
        appDummyDirective
    </div>
</template>