微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决尝试调用异步变量时,@ ViewChild组件未定义

我使用了@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
});

}

但是尝试调用异步变量 data 时,返回 undefind

我该怎么解决这个问题?

解决方法

在子组件中,您可以定义一个事件,以在数据发生如下变化时通知父项。

@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);
        });
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。