5

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!

yurzui
  • 205,937
  • 32
  • 433
  • 399
Breno
  • 53
  • 1
  • 1
  • 4

1 Answers1

17

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • 1
    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! – Breno Nov 28 '17 at 03:24
  • Plunker example is very nice! This is the power aka (complexity) that angular can achive – Bruno Miguel Mar 10 '23 at 11:11