【问题标题】:Emitting event from structural directive to parent component does not work从结构指令向父组件发出事件不起作用
【发布时间】:2017-10-29 08:36:02
【问题描述】:

作为问题的后续:Emit event from Directive to Parent element : Angular2

看起来当结构指令发出事件时,父组件没有收到它。

@Directive({ selector: '[appWidget]' })
export class WidgetDirective implements OnInit{
@Output() wdgInit: EventEmitter<any> = new EventEmitter();
@Input() set appWidget (wdg: any) {
    //display stuff
}
ngOnInit {
   this.wdgInit.emit();
}

widget.component.html:

  <ng-container *ngFor="let wdg of widgets">      
  <div *appTwitterWidget="wdg" >
  <ng-container>

widgetContainer.component.html:

 <app-widget [widgets]="widgetList" (wdgInit)="containerDoSomthing()"></app-widget>

在这种情况下,我发现 containerDoSomthing() 永远不会被调用。

【问题讨论】:

    标签: javascript angular typescript angular-directive


    【解决方案1】:

    这是可能的。问题是当前的 Angular 5.2.6 仍然不支持结构指令的 @Output 绑定,如果与问题中的糖化星号 (*) 语法(请参阅 GitHub issue)一起使用。

    要使其正常工作,您必须将其转换为脱糖形式 (see here),如下所示:

    <ng-template [appWidget]="wdg" (wdgInit)="containerDoSomthing($event)"></ng-template>
    

    【讨论】:

      【解决方案2】:

      我相信不可能将 EventEmitter 添加到结构指令中,因为指令引用的本地元素始终是注释!

      这可能是由于这个事实,事件从一开始就不会在 DOM 中生成...不过,这不是属性指令的问题,因为它们位于适当的 DOM 元素上。

      【讨论】:

        猜你喜欢
        • 2016-10-24
        • 2021-02-12
        • 2021-07-26
        • 1970-01-01
        • 2018-09-30
        • 2020-12-12
        • 2020-10-06
        • 2017-04-01
        • 1970-01-01
        相关资源
        最近更新 更多