Two ngcontent on a Angular component

Issue

I created a Tabs component (https://stackblitz.com/edit/angulartabs) used as follows:

<tabs>
  <tab title="tab 1">Content 1</tab>
  <tab title="tab 2" active="true">Content 2</tab>
</tabs>

The Tabs Component HTML is as follows:

<div class="head">
  <ul class="tabs">
    <li *ngFor="let tab of tabs" (click)="select(tab)" class="tab" [class.active]="tab.active">
      <a>{{ tab.title }}</a>
    </li>
  </ul>
  <div class="toolbar">Toolbar</div>
</div>
<ng-content></ng-content>

This is working but I also need the toolbar markup to change when selected tab changes.

So for each tab I need to define its content and its toolbar.

How to do this?

Update

Maybe the HTML markup when using the Tabs should be:

<tabs>
  <tab title="tab 1">
    <toolbar>Tab 1 toolbar</toolbar>
    Content 1
  </tab>
  <tab title="tab 2" active="true">
    Content 2
  </tab>
</tabs>

In tab 2 there is no toolbar which is also an option …

Does content also needs to be wrapped in a tag?

  <tab title="tab 1">
    <toolbar>Tab 1 toolbar</toolbar>
    <content>Content 1</content>
  </tab>

Solution

Update

I think I got a correct idea thanks to your stackblitz code.

It can be solved by CSS styling with ng-content translusion. Here are HTML codes with style attribute.

app.component.html:

<tabs>
  <tab title="tab 1">
    Content 1
    <div class="toolbar">Toolbar 1</div>
  </tab>
  <tab title="tab 2" active="true">
    Content 2
    <div class="toolbar">Toolbar 2</div>
  </tab>
</tabs>

tabs.component.html:

<div style="position: relative">
  <div class="head">
    <ul class="tabs">
      <li *ngFor="let tab of tabs" (click)="select(tab)" class="tab" [class.active]="tab.active">
        <a>{{ tab.title }}</a>
      </li>
    </ul>
  </div>
  <ng-content></ng-content>
</div>

tab.component.html:

<div *ngIf="active" style="position: absolute; right: 0; top: 0">
  <ng-content select=".toolbar"></ng-content>
</div>
<div [hidden]="!active" class="pane">
  <ng-content></ng-content>
</div>

This approach is not bad I think.

Answered By – zmag

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.