Angular-动态引用子组件

时间:2018-12-13 16:00:34

标签: angular

采用以下结构:

根:

<parent>
    <child>1st child content</child>
    <child>2nd child content</child>
</parent>

parent.html:

<ng-container *ngTemplateOutlet="children[currentChildIndex]"></ng-container><br/>

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:

<ng-content></ng-content>

child.ts:

public foo() {
    alert(`foo`)
  }

当我尝试从父级调用子级方法时:

this.children[0].foo()

我要

Cannot read property 'foo' of undefined

当然,孩子们也没有露面。

Not working example

1 个答案:

答案 0 :(得分:0)

显然,您必须使用ng-template,然后在视图中显示 template

将child.html更改为具有模板:

<ng-template><ng-content></ng-content></ng-template>

在child.ts中添加:

@ViewChild(TemplateRef) content: TemplateRef<any>;

在parent.html中更改为:

*ngTemplateOutlet="children[currentChildIndex].content"