ContentChildren 获取不到所有组件的解决办法

<app-content-child>
  <div class="head">
    这是头部
  <app-content-child-panel></app-content-child-panel>
  </div>
  <app-content-child-panel></app-content-child-panel>
  <app-content-child-panel></app-content-child-panel>
  <ul #list>
    <li>aaa</li>
    <li>bbb</li>
  </ul>
</app-content-child>
export class ContentChildComponent implements AfterViewInit {
  @ContentChildren(ContentChildPanelComponent) private panels: QueryList<ContentChildPanelComponent>;
  constructor() { }

  ngAfterViewInit(): void {
    console.log(this.panels); // 只有两个结果(只能获取到非div等元素包裹的结果)
  }

}

 

descendants属性

这是ContentChildren特有但属性,上个例子少拿类一个panel组件,原因是默认只寻找直属子panel 而.head里但panel组件,并非直属,所以拿不到,想要寻找到所有层级的panel组件,就开启descendants

@ContentChildren(ContentChildPanelComponent, { descendants: true }) private panels: QueryList;

posted @ 2023-03-16 13:37  赵辉Coder  阅读(28)  评论(0编辑  收藏  举报