简体   繁体   English

如何在Angular2 +中的ContentChildren QueryList中呈现1个孩子的内容

[英]How can I render content of 1 child from ContentChildren QueryList in Angular2+

I would like to render content from one element in QueryList filled by ContentChildren . 我想从ContentChildren填充的QueryList中的一个元素渲染内容。

Let's say I want to build tab component and this is my template for using such component: 假设我想构建制表符组件,这是我使用此类组件的模板:

<my-tabs>
  <my-tab title="title1">some content 1<my-tab>
  <my-tab title="title2">some content 2<my-tab>
</my-tabs>

My current tabs component html: 我当前的标签组件html:

<div class="header">
  <ul>
    <li> *ngFor="let tab of tabs, let i = index; let isLast = last">...<li>
  </ul>        
</div>
<!-- Missing !!! -->

Code: 码:

@ContentChildren(MyTabComponent) public tabs: QueryList<MyTabComponent>;

My problem is how can I render only active tab? 我的问题是如何只渲染活动标签? ( <!-- Missing !!! --> ) <!-- Missing !!! -->

I tried: 我试过了:

<ng-container [ngComponentOutlet]="tabs.toArray()[currentIndex].content"></ng-container>

<ng-container [ngTemplatetOutlet]="tabs.toArray()[currentIndex].content"></ng-container>    

<ng-container [ngComponentOutlet]="tabs.toArray()[currentIndex]"></ng-container>

<ng-container [ngTemplatetOutlet]="tabs.toArray()[currentIndex]"></ng-container>

But tab content is never rendered. 但是从不呈现标签内容。 my-tab component html is just: my-tab组件html只是:

<div>body</div>
<ng-template><ng-content></ng-content></ng-template>

at the moment. 在这一刻。

I check online how others are solving this problems, but everyone are using just <ng-content></ng-content> and then hides inactive tabs. 我在网上查看其他人如何解决这个问题,但每个人都只使用<ng-content></ng-content> ,然后隐藏非活动标签。
But I think better would be to render only needed content (better performance). 但我认为更好的是只渲染所需的内容(更好的性能)。

I also found this code where <ng-container [ngTemplateOutlet]="step.content"></ng-container> is used, but I tried this approach and it doesn't render anything. 我还发现了这个代码,其中使用了<ng-container [ngTemplateOutlet]="step.content"></ng-container> ,但我尝试了这种方法并且它没有呈现任何内容。

Edited: 编辑:
I also prepare stackblitz . 我也准备了stackblitz

Use ViewChild inside your StepComponent for storing element (in your case ng-template ): StepComponent使用ViewChild来存储元素(在你的情况下为ng-template ):

@Component({
    selector: "my-step",
    template: "<ng-template #innerTemplate><ng-content></ng-content></ng-template>",
})
export class StepComponent 
{
    @Input()
    public title;

    @ViewChild('innerTemplate') 
    public innerTemplate: TemplateRef<any>;
}

And set ngTemplateOutlet to that property in StepperComponent : 并在StepperComponent设置ngTemplateOutlet属性:

<ng-template [ngTemplateOutlet]="step.innerTemplate"></ng-template>

Here is the forked StackBlitz . 这是分叉的StackBlitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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