如何在angular4中使用嵌套组件?

时间:2018-05-15 10:04:15

标签: angular typescript

我正在寻找一个可以帮助我开发嵌套组件结构的解决方案。

例如:

<workBook>
    <workSheet [id]="1" [name]="'a'" [data]="111"></workSheet>
    <workSheet [id]="2" [name]="'b'" [data]="222"></workSheet>
    <workSheet [id]="3" [name]="'c'" [data]="333"></workSheet>
</workBook>

目前,我在工作簿组件中使用@contentChild,可以访问工作簿中的工作表属性。

工作表模板内容为:

<div> {{id}} -- {{name}} -- {{data}} </div>

如何在应用程序中显示此内容? 目前只能看到工作簿的内容。

提前谢谢

1 个答案:

答案 0 :(得分:0)

我认为你的workBook看起来像这样:

<div>WorkBook Title</div>
<ng-content></ng-content>

由于工作簿中有多个workSheet元素,如果要从包含workBook和workSheet的父组件访问子元素,则需要在WorkBookComponent中使用ContentChildren:

  @ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>;

  ngAfterContentInit() {
    // now you can access the contentChildren-array.
  }

如果您不需要在父组件中访问它们,只需将workSheet放在workBook的模板中并使用ViewChildren()而不是ContentChildren()