7

I'm trying to create a tab component using bootstrap.

<app-tabs> <app-tab [label]="'label1'">Description 1</app-tab> <app-tab [label]="'label2'">Description 2</app-tab> </app-tabs> 

I had a look at this article: https://juristr.com/blog/2016/02/learning-ng2-creating-tab-component/ but my use case is different.

I need to use a different <ng-content> in each loop of the for. This is my plunker: https://plnkr.co/edit/N2p8Vx?p=preview It prints both descriptions in the second tab, leaving the first one empty.

Appreciate any help!

1 Answer 1

18

You can take a look at how angular material implemented tabs control.

There are some caveats about this approach https://github.com/angular/angular/issues/18691 but anyway here is simplified version:

tab.component.ts

@Component({ selector: 'app-tab', template: ` <ng-template> <ng-content></ng-content> </ng-template>` }) export class TabComponent { ... @ViewChild(TemplateRef) template: TemplateRef<any>; } 

tabs.component.ts

<div *ngFor="let tab of tabs; let i = index" class="tab-pane" [ngClass]="{'active': i === 0}"...> <ng-container *ngTemplateOutlet="tab.template"></ng-container> </div> 

Plunker Example

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much @yurzui. That's the solution I was looking for. I had tried the *ngTemplateOutlet but I didn't realize I needed to put the TemplateRef in the TabComponent. Cheers!
Plunker example is very nice! This is the power aka (complexity) that angular can achive

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.