Pet*_*ter 7 javascript typescript angular angular10
所以我试图在我的组件中的特定位置显示子组件。
我有以下几点:
@Component({
selector: 'app-item-list',
template: `
<p *ngFor="let item of items">
{{item.order}}
<!-- display content of child component here -->
</p>`
})
export class ItemListComponent implements OnInit, AfterContentInit {
//Get all child components of the type ItemComponent and store them.
@ContentChildren(ItemComponent, {descendants: true})
items?: QueryList<ItemComponent>;
constructor() { }
ngOnInit() {
}
ngAfterContentInit(): void {
}
}
@Component({
selector: 'app-item',
template: `
<p>
item works!
</p>
<ng-content></ng-content>
`
})
export class ItemComponent implements OnInit {
@Input() order?: string;
constructor() { }
ngOnInit() {
}
}
Run Code Online (Sandbox Code Playgroud)
我试图使用它来显示它,<ng-content select="item">但这没有用。
具有以下内容:
<app-item-list>
<app-item order="2">
test2
</app-item>
<app-item order="1">
test1
</app-item>
</app-item-list>
Run Code Online (Sandbox Code Playgroud)
预期的输出是
2
item works!
test2
1
item works!
test1
Run Code Online (Sandbox Code Playgroud)
我可以向您推荐一个在 Angular 材料库中使用的解决方案。
app-item组件的内容包装在<ng-template>标签中item.component.html
<ng-template> <----------------------------- wrapper
<p>
item works!
</p>
<ng-content></ng-content>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
TemplateRefitem.component.ts
@ViewChild(TemplateRef, {static: true}) template: TemplateRef<any>;
Run Code Online (Sandbox Code Playgroud)
app-item-list组件循环中使用它项目列表.component.html
<p *ngFor="let item of items">
{{item.order}}
<ng-template [ngTemplateOutlet]="item.template"></ng-template>
</p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |