[英]Angular - reference child component dynamically
Giving the following structure: 给出以下结构:
root: 根:
<parent>
<child>1st child content</child>
<child>2nd child content</child>
</parent>
parent.html: parent.html:
<ng-container *ngTemplateOutlet="children[currentChildIndex]"></ng-container><br/>
parent.ts: parent.ts:
export class ParentComponent implements OnInit {
@ContentChildren(ChildComponent, { read: TemplateRef })
set childrenQueryList(val: QueryList<ChildComponent>) {
this.children = val.toArray();
}
children;
currentChildIndex = 0
child.html: child.html:
<ng-content></ng-content>
child.ts: child.ts:
public foo() {
alert(`foo`)
}
when I'm trying to call a child method from the parent like: 当我尝试从父级调用子级方法时,例如:
this.children[0].foo()
I'm getting 我越来越
Cannot read property 'foo' of undefined
and, of course, the children aren't showing. 而且,当然,孩子们没有出现。
Apparently, you have to use ng-template and then show the template in the view. 显然,您必须使用ng-template,然后在视图中显示该模板 。
Change child.html to have a template: 更改child.html以使其具有模板:
<ng-template><ng-content></ng-content></ng-template>
in child.ts add: 在child.ts中添加:
@ViewChild(TemplateRef) content: TemplateRef<any>;
in parent.html change to: 在parent.html中更改为:
*ngTemplateOutlet="children[currentChildIndex].content"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.