【发布时间】:2020-01-31 14:26:57
【问题描述】:
[步骤1] 我有一个对象“文章”,其中包含多个内容元素的数组。根据元素的类型(例如标题/图像),应显示不同的模板。如果没有必要,我不想为此明确拥有自己的组件,所以我猜测是否需要 ViewChild 或 ContentChild?
我已经查看了所有与 ngTemplate 相关的问题,但还没有找到解决方案。 我试图重写https://stackblitz.com/edit/angular-q1y2vz 来自ngTemplateOutlet with dynamic value,但目前失败。
component.ts
articles: any[] = [ {
"id_seq": "1234",
"content":[
{
"id": "123456",
"order": 0,
"type": "header",
"data":
{
"text": "loremipsum"
}
},
{
"id": "234567",
"order": 1,
"type": "image",
"data":
{
"url": "http://www.google.de/image.jpg"
}
}]
}]
component.html
<ng-container *ngFor="let content of articles[0]?.content;">
<ng-container [ngTemplateOutlet]="content?.type">
</ng-container>
</ng-container>
<ng-template #header >
<p>I'm a header</p>
</ng-template>
<ng-template #image >
<p>I'm an image</p>
</ng-template>
根据 ngTemplateOutlet 的语法和代码位置,我得到一个错误
templateRef.createEmbeddedView 不是函数
或者什么都不渲染。
如果我输入一个像“header”这样的静态字符串,它就可以工作。所以我猜,内容?。类型不是要走的路。 另一方面,这样的事情可以正常工作:
<accordion>
<accordion-group heading="articlecontent" [isOpen]="isFirstOpen">
<div class="accordion_no_side_margin">
<accordion-group *ngFor="let content of articles[0]?.content"
[heading]="content?.type">
{{ content?.id }}
{{ content?.order }}
{{ content?.type }}
{{ content?.data }}
</accordion-group>
</div>
</accordion-group>
</accordion>
[步骤2] 最终我确实想合并两个代码 sn-ps,以便 ng-template 应该在手风琴内执行。
[步骤3] 稍后我打算添加 ngTemplateOutletContext 并提供一些信息,但其他步骤应该可以正常工作。
目前我正在使用 @angular-devkit/core 8.1.3
【问题讨论】:
标签: angular accordion ngfor ng-template