Passing context to template through ngOutletContext in Angular2
After a long time, I made it.
Example with single value:
@Component({ selector: 'my-component', providers: [], template: ` <template [ngTemplateOutlet]="templ" [ngOutletContext]="{isVisible: true}"> </template> `})export class MyElementComponent implements OnInit { @ContentChild(TemplateRef) templ; constructor(){}}<my-component> <template let-isVisible="isVisible"> {{isVisible ? 'yes!' : 'no'}} </template></my-component>
Example with loop:
@Component({ selector: 'my-component', providers: [], template: ` <div *ngFor="let element of data"> <template [ngTemplateOutlet]="templ" [ngOutletContext]="{element: element}"> </template> </div> `})export class MyElementComponent implements OnInit { @ContentChild(TemplateRef) templ; constructor(){ this.data = [{name:'John'}, {name:'Jacob'}]; }}--- <my-component> <template let-element="element"> {{element.name}} </template></my-component>
Result:
<div>John</div><div>Jacob</div>
Heads up ngOutletContext is deprecated and renamed as ngTemplateOutletContext.
Search the change log for "NgTemplateOutlet#ngTemplateOutletContext"