【发布时间】:2019-05-14 21:31:23
【问题描述】:
给出以下结构:
根:
<parent>
<child>1st child content</child>
<child>2nd child content</child>
</parent>
父.html:
<ng-container *ngTemplateOutlet="children[currentChildIndex]"></ng-container><br/>
父.ts:
export class ParentComponent implements OnInit {
@ContentChildren(ChildComponent, { read: TemplateRef })
set childrenQueryList(val: QueryList<ChildComponent>) {
this.children = val.toArray();
}
children;
currentChildIndex = 0
child.html:
<ng-content></ng-content>
child.ts:
public foo() {
alert(`foo`)
}
当我试图从父类调用子方法时:
this.children[0].foo()
我明白了
Cannot read property 'foo' of undefined
当然,孩子们没有出现。
【问题讨论】:
-
您的演示链接似乎没有任何父子组件
-
已修复。谢谢
-
@ContentChildren(ChildComponent, { read: TemplateRef }),你不应该阅读 TemplateRef;尝试使用 ngComponentOutlet 在 html 文件中删除它
-
@ABOS 谢谢,但没用。只有在研究了角度材料 impl 之后。我想通了
标签: angular