Angular 2: capture events from ng content
Angular Application Structure:
<app><div content><a href="#" (click)="show()">click me</a></div></app> Content Component Template:
<ng-content></ng-content> The content component has a public show() method, but when I click this link, I get:
Error: EXCEPTION: Error during evaluation of "click" ORIGINAL EXCEPTION: TypeError: l_context.show is not a function ORIGINAL STACKTRACE: anonymous/ ChangeDetector_AppComponent_0.prototype.handleEventInternal@http ://localhost:3000/node_modules/angular2/bundles/angular2.dev.js line 10897 > Function:207:13 AbstractChangeDetector</ AbstractChangeDetector.prototype.handleEvent@http ://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:8788:17 Basically I want to reuse page layout and place listeners on an existing dom, I don't want to create additional templates or components. Perhaps I missed something obvious.
show() resolves to the parent component <app> , and since it looks like <app> , is the root component, there is no parent.
I assume the error here is that Angular is even trying to bind the click event. I got the impression that <ng-content> is not supported at all in the root component.
See also https://github.com/angular/angular/issues/1858 ( https://github.com/angular/angular/issues/6046 )
Update
<h1>Angular</h1> <div content #contentRef> <ui> <li><a href="#" (click)="contentRef.show($event)" class="link" button>link 1</a></li> <li><a href="#" (click)="contentRef.show($event)" class="link" button>link 2</a></li> <li><a href="#" (click)="contentRef.show($event)" class="link" button>link 3</a></li> </ui> </div> bindings are allowed inside the component in which they are declared. In the above example, I explicitly redirected the link to the ContentComponent by creating the template variable #contentRef in the target element and referring to it when defining the click handler (click)="contentRef.show($event)" .
Even though the content is transferred to another component using <ng-content> , this does not mean that the scope of change is changing. <ng-content> is just a projection - the elements are displayed elsewhere, all of them are still โownedโ by the component where they were originally added.