【问题标题】:Output of custom directive is not received未收到自定义指令的输出
【发布时间】:2017-01-31 12:30:21
【问题描述】:

我正在尝试从自定义指令接收事件,但它不起作用。我的应用程序中有几个组件可以成功发送事件,所以我做了一个小例子:

<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);
    }
}

我的指令哪里出错了?

【问题讨论】:

  • 意味着你不能在指令上使用@Output 装饰器?
  • 您确定需要 structural 指令吗?你不能用appDummyDirective代替*appDummyDirective吗?
  • @stj242 如果不能使用@Output
  • @AngularFrance:是的,它需要是结构化的,因为我的真实世界指令模仿 ngFor。
  • 你得到什么错误?

标签: angular angular2-directives


【解决方案1】:

显然@Output 不适用于* 的语法糖。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多