简体   繁体   English

尝试调用异步变量时@ViewChild 组件未定义

[英]@ViewChild component undefined when trying to call async variable

I used @ViewChildren component:我使用了@ViewChildren 组件:

@ViewChildren("MyTest2Component") public myTest2Component: QueryList<MyTest2Component>


public ngAfterViewInit() {

this.myTest2Component.changes.subscribe((comps: QueryList <MyTest2Component>) =>
{
    console.log(comps.first.data); // data is async, here is undefind
});

} }

but when trying to call async variable data , return undefind但是当试图调用异步变量数据时,返回undefin

What can I do to solve this problem?我能做些什么来解决这个问题?

In your child component, you can define an event to notify the parent when the data changes as below.在您的子组件中,您可以定义一个事件来在数据发生变化时通知父组件,如下所示。

@Component({
  selector: 'parent-component',
  template: '<child-component (dataChanged)="onChildDataChanged($event)"></child-component>',
  styles: ['']
})
export class ParentComponent {
    onChildDataChanged(newData) {
        // tweak with new data
    }
}

@Component({
  selector: 'child-component',
  template: '<div></div>',
  styles: ['']
})
export class ChildComponent implements OnInit {
    @Output() dataChanged: EventEmitter<any> = new EventEmitter<any>();
    
    ngOnInit(): void {
        someAsyncOperation.subscribe(data => {
            this.dataChanged.emit(data);
        });
    }
}

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

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