简体   繁体   中英

Angular Create Multiple Template Instances

I have a tabs control with tabs that are generated dynamically, and something like this in my markup for getting the correct template for the current tab.

      <ng-container *ngIf="(tabSelected | async); let selectedTab">
        <view-area [template]="getTemplate(selectedTab)"></view-area>
      </ng-container>

      <ng-template name="dashboard">
        <dashboard></dashboard>
      </ng-template>

      <ng-template name="users">
        <users></users>
      </ng-template>

      <ng-template name="group-builder">
        <group-builder></group-builder>
      </ng-template>

This is works fine, but some of these templates take a while to initialise and I can have multiple tabs that use the same templates, so switching tabs can have a bit of a delay. Any ideas on how I can effectively create multiple template instances of the same template?

I know that normally you would just enumerate the tabs with their own <ng-content> but the tabs here are a completely separate component.

This was actually really easy if anyone needs this. Basically enumerate all of the options with ng-container with a ngTemplateOutlet and just set either display: none for hidden or display: block for the selected item. This will then cache all of the rendered templates and they will display instantly when switching tabs without losing state.

<ng-container *ngFor="let sideBarOption of (sideBar.allItems | async)">
    <div [ngStyle]="getTemplateVisibility(tabSelected.value , sideBarOption)">
        <ng-container [ngTemplateOutlet]="getTemplate(sideBarOption)"></ng-container>
    </div>
</ng-container>

<ng-template name="dashboard">
    <dashboard></dashboard>
</ng-template>

<ng-template name="users">
    <users></users>
</ng-template>

<ng-template name="group-builder">
    <group-builder></group-builder>
</ng-template>

And in the component ts file

public getTemplateVisibility(selected: SidebarOption, sideBarOption: SidebarOption): any {
    return {
      display: selected === sideBarOption ? 'block' : 'none'
    };
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM