我尝试用下面的方式列出静态的(和动态的,但这是一个不同的问题)组件。(这既适用于我们需要其标题作为模板的选项卡,以允许按钮、自定义格式等,也适用于内容列表和其他类似内容)
我的父组件从子组件列表开始,每个子组件包含两个不同的子组件:
<parent>
<child>
<grandchild-1>child 1</grandchild-1>
<grandchild-2>child 1 extended content</grandchild-2>
</child>
<child>
<grandchild-1>child 2</grandchild-1>
<grandchild-2>child 2 extended content</grandchild-2>
</child>
</parent>
现在我想首先列出所有的孙子-1(在ul中,每个在安莉中),然后列出所有的孙子-2的:
<ul>
<li (click)="parentMethod()">child 1</li>
<li (click)="parentMethod()">child 2</li>
</ul>
<div>child 1 extended content</div>
<div>child 2 extended content</div>
我可以很容易地列出孙子-2通过设置父母的模板为:
<ng-content></ng-content>
将子组件的模板添加到:
<div>
<ng-content select="grandchild-2"></ng-content>
</div>
但似乎不知道如何处理孙子组件-1的先前列表。有关此(静态)列表问题的完整代码列表,请参阅https://stackblitz.com/edit/angular-38xf2q。
我一直在使用ng-template
(在子组件模板中的grandchild-1
组件周围添加它)和ng-container
(在父模板的<ul>
中,并迭代子组件,尝试添加它们的grandchild-1
模板)。看起来这应该有一个如此简单的解决方案。
发布于 2018-06-01 09:16:12
我终于弄明白了(经过几个小时的尝试,当然就在发布之后),但如果有人有更好的解决方案……
在子模板中,围绕grandchild-1
内容创建一个ng-template
,这样完整的子模板html将变为:
<ng-template #granchild1TemplateRef>
<ng-content select="grandchild-1"></ng-content>
</ng-template>
<div><ng-content select="grandchild-2"></ng-content></div>
现在,在子类中,获取此TemplateRef
的句柄
export class ChildComponent {
@ViewChild('granchild1TemplateRef') public Granchild1TemplateRef: TemplateRef<Grandchild1Component>;
}
现在我们有了子目录的TemplateRef
,我们可以把它注入到父目录的列表ng-container
中,这样父目录的完整模板html就变成了:
<ul>
<li *ngFor="let child of children">
<ng-container *ngTemplateOutlet="child.Granchild1TemplateRef"></ng-container>
</li>
</ul>
<ng-content></ng-content>
https://stackoverflow.com/questions/50634470
复制相似问题