【问题标题】:ng-content in for loopfor 循环中的 ng-content
【发布时间】:2018-05-10 04:35:59
【问题描述】:

我正在尝试使用引导程序创建一个选项卡组件。

<app-tabs>
  <app-tab [label]="'label1'">Description 1</app-tab>
  <app-tab [label]="'label2'">Description 2</app-tab>
</app-tabs>

我看过这篇文章: https://juristr.com/blog/2016/02/learning-ng2-creating-tab-component/ 但我的用例不同。

我需要在 for 的每个循环中使用不同的 &lt;ng-content&gt;。 这是我的笨蛋:https://plnkr.co/edit/N2p8Vx?p=preview 它在第二个选项卡中打印两个描述,而第一个为空。

感谢任何帮助!

【问题讨论】:

    标签: angular angular2-ngcontent


    【解决方案1】:

    你可以看看 angular material 是如何实现标签控制的。

    关于这种方法https://github.com/angular/angular/issues/18691 有一些注意事项,但无论如何这里是简化版:

    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。这就是我一直在寻找的解决方案。我曾尝试过*ngTemplateOutlet,但我没有意识到我需要将 TemplateRef 放在 TabComponent 中。干杯!
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2021-07-30
    相关资源
    最近更新 更多