Pass Data to a Dynamic ng-template

Our tabs are working quite well now, but what we really want to do is pass some data from the outside and render it dynamically. To do this, we can use ngTemplateOutletContext to pass in the data to the ng-template .

First, go to the tab.component.ts file and add a new Input() inside the TabComponent task. This Input() is going to pass in the data from the outside.

export class TabComponent {

@Input() tabTitle: string;

@Input() active = false;

@Input() template;

@Input() dataContext;

}

We now need to pass on this data on to our template. This is done using the ngtemplateOutletContext property on the ng-container component.

<ng-container

*ngIf="template"

[ngTemplateOutlet]="template"

[ngTemplateOutletContext]="{data: dataContext}"

></ng-container>

The reason I am using an object to pass on the dataContext to the property is that I then get the choice of extending this property so it can take on other types of data.

Now go to the app.component.ts file and leverage the dataContext inside the second ngx-tab component.

<ngx-tab

tabTitle="Hero"

[template]="hello"

[dataContext="heroes[0]"]

></ngx-tab>

We only have one entry inside the heroes array. This data gets passed in, and then, inside the ngx-tab component, we’ll pass it along to our template, which, in this case, resides here.

Now we can leverage this data object and use it inside our component. I want to visualize that person’s name, so I would do something like hero?.name . The ? is placed here in case the hero is undefined. We also need to define the hero as data .

<ng-template #hello let-hero="data">

Hello, {{hero?.name}}

</ng-template>

Once your browser refreshes, jump to the second tab and you will see that the name gets properly visualized.