繁体   English   中英

Angular:为什么带有 QueryList 的 ViewChild 只返回第一个实例?

[英]Angular: Why is ViewChild with QueryList returning only the first instance?

我有一个名为Component1的 Angular Component1 它包含同一组件的多个嵌套实例,如下所示:

<div>
  <ng-container *ngFor='let item of items'>
    <component-1>
  </ng-container>
</div>

项目中的所有 5 个items都被显示,所以我知道它们在那里。 但是,当我尝试检索包含Component1所有 5 个实例的数组时,如下所示:

@ViewChild(Component1) children: QueryList<Component1>;

然后children ,而不是包含一个Component1的数组,只包含一个Component1 :5 个中的第一个。

有谁知道为什么会这样?

您将需要使用@ViewChildren

用于从视图 DOM 中获取元素或指令的 QueryList。 每当添加、删除或移动子元素时,查询列表都会更新,查询列表的可观察更改将发出一个新值。

@ViewChildren(Component1) children: QueryList<Component1>;

ViewChild只返回第一项。

配置视图查询的属性装饰器。 变更检测器在视图 DOM 中查找与选择器匹配的第一个元素或指令。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM