![](/img/trans.png)
[英]Angular2+ how to get proper element order from QueryList<>
[英]How can I render content of 1 child from ContentChildren QueryList in Angular2+
我想從ContentChildren
填充的QueryList中的一個元素渲染內容。
假設我想構建制表符組件,這是我使用此類組件的模板:
<my-tabs>
<my-tab title="title1">some content 1<my-tab>
<my-tab title="title2">some content 2<my-tab>
</my-tabs>
我當前的標簽組件html:
<div class="header">
<ul>
<li> *ngFor="let tab of tabs, let i = index; let isLast = last">...<li>
</ul>
</div>
<!-- Missing !!! -->
碼:
@ContentChildren(MyTabComponent) public tabs: QueryList<MyTabComponent>;
我的問題是如何只渲染活動標簽? ( <!-- Missing !!! -->
)
我試過了:
<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>
但是從不呈現標簽內容。 my-tab
組件html只是:
<div>body</div>
<ng-template><ng-content></ng-content></ng-template>
在這一刻。
我在網上查看其他人如何解決這個問題,但每個人都只使用<ng-content></ng-content>
,然后隱藏非活動標簽。
但我認為更好的是只渲染所需的內容(更好的性能)。
我還發現了這個代碼,其中使用了<ng-container [ngTemplateOutlet]="step.content"></ng-container>
,但我嘗試了這種方法並且它沒有呈現任何內容。
編輯:
我也准備了stackblitz 。
在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>;
}
並在StepperComponent
設置ngTemplateOutlet
屬性:
<ng-template [ngTemplateOutlet]="step.innerTemplate"></ng-template>
這是分叉的StackBlitz 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.