[英]Angular: Why is ViewChild with QueryList returning only the first instance?
I have an Angular component called Component1
.我有一个名为
Component1
的 Angular Component1
。 It contains several nested instances of the same component, like this:它包含同一组件的多个嵌套实例,如下所示:
<div>
<ng-container *ngFor='let item of items'>
<component-1>
</ng-container>
</div>
All 5 items in items
are being displayed, so I know they're there.项目中的所有 5 个
items
都被显示,所以我知道它们在那里。 However, when I try to retrieve an array containing all 5 instances of Component1
like this:但是,当我尝试检索包含
Component1
所有 5 个实例的数组时,如下所示:
@ViewChild(Component1) children: QueryList<Component1>;
then children
, instead of containing an array of Component1
s, contains only one Component1
: the first of the 5.然后
children
,而不是包含一个Component1
的数组,只包含一个Component1
:5 个中的第一个。
Anyone know why this would be?有谁知道为什么会这样?
You will need to use @ViewChildren您将需要使用@ViewChildren
Use to get the QueryList of elements or directives from the view DOM.
用于从视图 DOM 中获取元素或指令的 QueryList。 Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.
每当添加、删除或移动子元素时,查询列表都会更新,查询列表的可观察更改将发出一个新值。
@ViewChildren(Component1) children: QueryList<Component1>;
ViewChild
only returns the first item. ViewChild
只返回第一项。
Property decorator that configures a view query.
配置视图查询的属性装饰器。 The change detector looks for the first element or the directive matching the selector in the view DOM.
变更检测器在视图 DOM 中查找与选择器匹配的第一个元素或指令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.