Reusing content of Angular ngb-tabs in multiple tabs with ngTemplateOutlet or something else

1.1k Views Asked by At

I am using Angular ng-tabset to render some tabs. My ngb-tab looks somewhat like:

<ngb-tab id="mytabs">
    <ng-template ngbTabTitle>
        <div data-locator="xxxe">yyy</div>
    </ng-template>
    <ng-template ngbTabContent>
        ...
        ...
        ...
    </ng-template>
</ngb-tab>

which works fine. But I have a couple of other tabs also in this template where I want the same content rendered. so, for the purpose of re-usability, I was trying to move the contents of the tab separate and use it's reference in each tab where I want that rendered. I am not sure how to do it. I tried putting it inside a separate <ng-template> as:

<ng-template #testing>
    <ng-template ngbTabTitle>
        <div data-locator="xxxe">yyy</div>
    </ng-template>
    <ng-template ngbTabContent>
        ...
        ...
        ...
    </ng-template>
<ng-template

and under tab, where I need this rendered, I try to call it as:

<ngb-tab id="mytabs">
    <ng-container *ngTemplateOutlet="testing"></ng-container>    // referring the #testing above
</ngb-tab>

OR:

<ngb-tab id="mytabs">
    <ng-template *ngTemplateOutlet="testing"></ng-template>
</ngb-tab>

But my tabs are not rendered. Maybe its wrong approach or I am missing something. Is it possible to achieve what I am trying to achieve? If yes, how?

2

There are 2 best solutions below

5
Berk Kurkcuoglu On

I would suggest not nesting the ng-templates and use them with different ids, then inserting them under ngb-tab separately like this:

<ng-template ngbTabTitle #testTitle>
    <div data-locator="xxxe">yyy</div>
</ng-template>
<ng-template ngbTabContent #testContent>
    ...
    ...
    ...
</ng-template>
<ngb-tab id="mytabs">
    <ng-container *ngTemplateOutlet="testTitle"></ng-container>    
    <ng-container *ngTemplateOutlet="testContent"></ng-container>
</ngb-tab>
0
Marc On

I hope that I understand your question right. For re-usability of templates you can create you own components. For re-usability of logic you can create services.

<ngb-tab id="mytabs">
    <ng-template ngbTabTitle>
        <my-xyz-comp data-locator="xxxe"></my-xyz-comp>
    </ng-template>
    <ng-template ngbTabContent>
        <my-xyz-comp data-locator="aaaa"></my-xyz-comp>
    </ng-template>
</ngb-tab>