[英]Angular how to loop throught QueryList with ViewChildren?
I have child components in ngFor:我在 ngFor 中有子组件:
@ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>;
Then i want to loop throught that QueryList:然后我想遍历那个 QueryList:
console.log(this.singleMultiSelections) // 1 item in _results , but results are private
for(let component of this.singleMultiSelections){
console.log(component); //Not Working
}
There is nothing wrong with your code per se.您的代码本身没有任何问题。
QueryList implements Iterable, so you can use methods such as forEach
, map
, and for (let i of items)
on it. QueryList 实现了 Iterable,因此您可以在其上使用
forEach
、 map
和for (let i of items)
等方法。 You can view this in more detail in the Angular Documentation .您可以在Angular 文档中查看更多详细信息。
Keep in mind that for the QueryList to produce the expected results, you can only call it after the LifeCycle hook AfterViewInit
has been called.请记住,要让 QueryList 产生预期的结果,您只能在调用 LifeCycle 挂钩
AfterViewInit
之后调用它。 Until then the list will not have been loaded, you read the official notes .在那之前列表不会被加载,你阅读官方说明。
You can do so like this:你可以这样做:
@ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>;
onAfterViewInit() {
for(let component of this.singleMultiSelections){
// Code here
}
}
Firstly, it depends where you are calling it from.首先,这取决于您从哪里调用它。 Probably you will have to call it in ngAfterViewInit when all the components are instantiated.
当所有组件都被实例化时,您可能必须在 ngAfterViewInit 中调用它。 If you are calling before that, those components might not yet exist
如果您在此之前调用,这些组件可能还不存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.