簡體   English   中英

嘗試調用異步變量時@ViewChild 組件未定義

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

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

}

但是當試圖調用異步變量數據時,返回undefin

我能做些什么來解決這個問題?

在您的子組件中,您可以定義一個事件來在數據發生變化時通知父組件,如下所示。

@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