首页 > 解决方案 > 在 ngFor 中获取对子组件的引用

问题描述

我有一个父组件 ( ParentComponent) 和一个子组件 ( ChildComponent)。

我想为所有孩子构建一个 QueryList,以便我可以isOpen在其中一些上设置属性。孩子们在 an 中,*ngFor我无法得到任何@ContentChildren,或工作——他们总是以空数组的形式返回。@ContentChild@ViewChildren@viewChild

父组件控制器

import { Component, ContentChild, ContentChildren, OnInit, QueryList, ViewChild,  ViewChildren } from '@angular/core';
import { ChildComponent } from '../child/child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  @ContentChildren(ChildComponent, { descendants: true }) childrenRef: QueryList<ChildComponent>;
  children: QueryList<ChildComponent>;

  items = [1, 3, 4, 4, 5];

  constructor() { }

  ngOnInit(): void {
    console.info(this.childrenRef);
  }

  ngAfterContentInit(): void {
    this.children = this.childrenRef;
    console.info(this.childrenRef, this.childrenRef.length);
    console.info(this.children, this.children.length);
  }
}

父组件模板

<app-child *ngFor="let item of items"></app-child>

https://stackblitz.com/edit/atw-angular-select-child-component?file=src%2Fapp%2Fparent%2Fparent.component.ts

我怀疑我要么完全错误地处理这个问题,要么我从根本上误解了一些东西。

标签: angular

解决方案


推荐阅读