Angular 角度@ContentChildren不´;t与<;ng模板>;

Angular 角度@ContentChildren不´;t与<;ng模板>;,angular,recursion,angular-template,Angular,Recursion,Angular Template,我正在尝试创建一个角度的树组件,如下所示: @Component({ selector: 'app-tree', template: ` <div style.padding-left.px="{{depth*20}}"> <ng-content></ng-content> </div> ` }) export class TreeComponent implements AfterContentInit {

我正在尝试创建一个角度的树组件,如下所示:

@Component({
  selector: 'app-tree',
  template: `
    <div style.padding-left.px="{{depth*20}}">
      <ng-content></ng-content>
    </div>
  `
})
export class TreeComponent implements AfterContentInit {
  private _depth = 0;
  get depth() {
    return this._depth;
  }
  set depth(value: number) {
    this._depth = value;
    this.updateChildren();
  }

  @Input() isRoot: boolean;

  @ContentChildren(TreeComponent) children: QueryList<TreeComponent>;

  ngAfterContentInit() {
    if (this.isRoot) {
      console.log('i am root', this.children.filter(tree => tree !== this).length);
      this.updateChildren();
    }
  }

  private updateChildren() {
    this.children
      .filter(tree => tree !== this)
      .forEach(branch => {
        branch.depth = this.depth + 1;
      });
  }
}
<app-tree [isRoot]="true">
  Label 1
  <app-tree>
    Label 1.1
  </app-tree>
  <app-tree>
    Label 1.2
    <app-tree>
      Label 1.2.1
    </app-tree>
  </app-tree>
  <app-tree>
    Label 1.3
  </app-tree>
</app-tree>
treeModel = [
  {
    text: 'Lorem ipsum',
    children: [
      {
        text: 'Lorem ipsum',
        children: [
          {
            text: 'Lorem ipsum',
            children: [
              { text: 'Lorem ipsum' },
              { text: 'Lorem ipsum' },
              { text: 'Lorem ipsum' }
            ]
          },
          { text: 'Lorem ipsum' },
          { text: 'Lorem ipsum' },
          { text: 'Lorem ipsum' }
        ]
      },
      { text: 'Lorem ipsum' },
      { text: 'Lorem ipsum' },
      { text: 'Lorem ipsum' }
    ]
  }
];
这不起作用,因为从模板渲染树。在
ng模板
中包装组件时,
@ContentChildren
似乎无法找到从模板渲染的子级

这是预期的吗?有什么可能的解决办法和变通办法吗

另一个问题(尽管问题不大)是ContentChildren包含主机组件;因此
this.children.filter(tree=>tree!==this)

指向Plunker的链接:

此问题有一个解决方案

在链接中,报告问题的人提供了一个解决方法,但我发现它相当麻烦,我相信它会导致性能不佳

treeModel = [
  {
    text: 'Lorem ipsum',
    children: [
      {
        text: 'Lorem ipsum',
        children: [
          {
            text: 'Lorem ipsum',
            children: [
              { text: 'Lorem ipsum' },
              { text: 'Lorem ipsum' },
              { text: 'Lorem ipsum' }
            ]
          },
          { text: 'Lorem ipsum' },
          { text: 'Lorem ipsum' },
          { text: 'Lorem ipsum' }
        ]
      },
      { text: 'Lorem ipsum' },
      { text: 'Lorem ipsum' },
      { text: 'Lorem ipsum' }
    ]
  }
];