[英]Render elements of QueryList in the template
I have two components: items-list and item 我有两个组件: items-list和item
I use them like this: 我这样使用它们:
<items-list items="items"></items-list>
On the inner level items-list looks like this: 在内部级别item-list看起来像这样:
<ngx-carousel>
<ngx-item *ngFor="let item of items">
<item data="item"></item>
</ngx-item>
</ngx-carousel>
However this approach is not flexible because I should use some "items" array to populate items. 但是这种方法不灵活,因为我应该使用一些“items”数组来填充项目。
What I want to do is to rework the approach like this: 我想要做的是重写这样的方法:
<items-list>
<item data="dataForFirstItem"></item>
<item data="dataForSecondItem"></item>
</items-list>
But the problem here is that I don' understand how to rework the implementation of items-list : 但这里的问题是我不明白如何重新设计items-list的实现:
<ngx-carousel>
<ngx-item *ngFor="let item of items">
<!-- each item should be rendered here -->
</ngx-item>
</ngx-carousel>
ngx-item requires component to be placed inside. ngx-item需要将组件放在里面。
I used ContentChildren to capture all rendered item components in QueryList. 我使用ContentChildren捕获QueryList中的所有呈现的项目组件。 But how to render each item inside the ngx-item ?
但是如何渲染ngx项目中的每个项目?
You can't render QueryList
returned by ContentChildren
directly, but if each item has a reference for it's own ng-template
, then it can be rendered with *ngTemplateOutlet
. 你无法呈现
QueryList
由归国ContentChildren
直接,但如果每个项目都有它自己的参考ng-template
,那么就可以用渲染*ngTemplateOutlet
。
Full example at Stackblitz. Stackblitz的完整示例。
//itemsList.component.ts
import {QueryList, ViewChildren, Component, ContentChildren} from '@angular/core'
import {Item} from './item.component'
@Component({
selector: 'items-list',
template: `
List of items:
<ul>
<li *ngFor='let item of items'>
<ng-container *ngTemplateOutlet='item.template'></ng-container>
</li>
</ul>
`
})
export class ItemsList {
@ContentChildren(Item)
items: QueryList<Item>
}
//item.component.ts
import {Component, ViewChild, TemplateRef, Input} from '@angular/core'
@Component({
selector: 'item',
template: `<ng-template #itemTemplate>Item data: {{itemData}}</ng-template>`
})
export class Item {
@Input()
itemData: number
@ViewChild('itemTemplate')
template: TemplateRef<any>
}
//app.component.html
<items-list>
<item [itemData]='1'></item>
<item [itemData]='2'></item>
</items-list>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.