10

As a follow up to question: Emit event from Directive to Parent element : Angular2

It looks like when a structural directive emits an event, the parent component does not receive it.

@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>

In this case I find containerDoSomthing() never getting called.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
nesdis
  • 1,182
  • 13
  • 16

2 Answers2

18

It's possible. The issue is that current Angular 5.2.6 still doesn't support @Output binding for structural directives if used with the sugared asterisk (*) syntax (see GitHub issue) like in the question.

To make it work you have to transform it to de-sugarized form (see here) like this:

<ng-template [appWidget]="wdg" (wdgInit)="containerDoSomthing($event)"></ng-template>
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
1

I believe it is not possible to add an EventEmitter to a structural directive, simply because the native element that the directive references, is always a comment!

It is probably due to this fact that, an event never gets generated in the DOM in the first place... This is not a problem with attribute directives though, as they sit on a proper DOM element.

nesdis
  • 1,182
  • 13
  • 16