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;
Run Code Online (Sandbox Code Playgroud)
您好,如上所述,我<app-child>
在使用ngFor呈现的Parent组件中有几个组件.我想访问父组件中的每个子组件的方法.但是,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
Run Code Online (Sandbox Code Playgroud)
查询列表中似乎有两个_results属性,第一个是空的,第二个有4个对子组件的引用.
我该如何提取?
ksh*_*iya 12
Nvm,我想通了,QueryList 具有您可以订阅的更改属性。我的猜测是当 NgFor 呈现组件时, subscribe 方法返回组件。
this.children.changes.subscribe(c => { c.toArray().forEach(item => {
console.log(item);}) });
Run Code Online (Sandbox Code Playgroud)
您必须订阅 ViewChildren 的更改,如 @kshatriiya 提到的。
viewChildren 的初始化必须进入 ngAfterViewInit 内部并等待下一个 javascript 事件周期进行初始化。
Please find working prototype here - https://plnkr.co/edit/fBR3CtJ4wYfcPnIISVPW?p=preview
Run Code Online (Sandbox Code Playgroud)
如果您需要更多了解ViewChild、ViewChildren、ContentChild、ContentChildren的用法,请阅读此博客,谢谢!
归档时间: |
|
查看次数: |
5712 次 |
最近记录: |