【问题标题】:Angular - reference child component dynamicallyAngular - 动态引用子组件
【发布时间】: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

当然,孩子们没有出现。

Not working example

【问题讨论】:

  • 您的演示链接似乎没有任何父子组件
  • 已修复。谢谢
  • @ContentChildren(ChildComponent, { read: TemplateRef }),你不应该阅读 TemplateRef;尝试使用 ngComponentOutlet 在 html 文件中删除它
  • @ABOS 谢谢,但没用。只有在研究了角度材料 impl 之后。我想通了

标签: angular


【解决方案1】:

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

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

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

在 child.ts 中添加:

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

在 parent.html 中更改为:

*ngTemplateOutlet="children[currentChildIndex].content"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多