angular - 在 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>
我怀疑我要么完全错误地处理这个问题,要么我从根本上误解了一些东西。
解决方案
推荐阅读
- django - 如何在模板(django)中显示在线好友总数?
- android - Recyclerview 的问题。recyclerview.xml 不能为空
- android - Android:Imageview在上面对象的高度被改变时被调整大小
- pine-script - Pine-Script:从已知范围中选择一个栏 [仅]
- c++ - 函数 C++ 的多重声明
- excel - 从另一张纸上的单元格中获取价值
- directus - Directus - 在挂钩中创建文件
- javascript - 保存新创建的角色和频道的 ID
- javascript - Firebase 实时数据库规则在前端不起作用
- javascript - 如何在 Firebase Cloud Function 条件下使用模板文字