ng-content in for loop

泪湿孤枕 提交于 2019-11-30 14:25:04

问题


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:


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



来源:https://stackoverflow.com/questions/47502461/ng-content-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!