使用* ngFor渲染子项时,@ ViewChildren Querylist Array为空

问题描述 投票:6回答:2
import { Component, OnInit, ViewChildren } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
    selector: 'app-parent'
    styleUrls: [],
    templateUrl: `<div>
                    <app-child *ngFor="let data of datas" [data]="data"></app-
                    child>
                  <div>'

export class ParentComponent implements OnInit {

@ViewChildren(ChildComponent) children;

你好,如上所述我在使用ngFor渲染的Parent组件中有几个<app-child>组件。我想访问父组件中的每个子组件的方法。但是,Querylist继续返回一个空数组。

请注意,父组件和子组件都已在单独的根组件的app-module中声明。当父级的“数据”字段被填充/更改时,子组件没有问题。问题是我无法捕获@ViewChildren装饰器属性中呈现的Child组件。

编辑:这是控制台日志:

QueryList {dirty: false, _results: Array(0), changes: EventEmitter}changes: 
EventEmitter {_isScalar: false, observers: Array(0), closed: false, 
isStopped: false, hasError: false, …}dirty: falsefirst: (...)last: 
(...)length: (...)_results: (4) [AnswerButtonComponent, 
AnswerButtonComponent, AnswerButtonComponent, 
AnswerButtonComponent]__proto__: Object

查询列表中似乎有两个_results属性,第一个是空的,第二个有4个对子组件的引用。

我该如何提取?

angular
2个回答
2
投票

您必须订阅ViewChildren的更改,如@kshatriiya所述。

viewChildren的初始化必须进入ngAfterViewInit并等待下一个javascript事件周期进行初始化。

Please find working prototype here - https://plnkr.co/edit/fBR3CtJ4wYfcPnIISVPW?p=preview

如果您需要更深入了解ViewChild,ViewChildren,ContentChild,ContentChildren的用法,请阅读此blog谢谢!


1
投票

Nvm,我想通了,QueryList有你可以订阅的更改属性。我的猜测是当NgFor渲染组件时,subscribe方法返回组件。

this.children.changes.subscribe(c => { c.toArray().forEach(item => { 
console.log(item);}) });
© www.soinside.com 2019 - 2024. All rights reserved.