0

I used @ViewChildren component:

@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

What can I do to solve this problem?

Mahdi
  • 307
  • 6
  • 19

1 Answers1

4

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);
        });
    }
}
ilkengin
  • 191
  • 1
  • 4
  • 12
  • MyTest2Component is a package and I cant change its. – Mahdi Oct 28 '20 at 08:29
  • 1
    This is sad... Then, the only way out is to check perodically whether the data is populated using `setInterval` and you can use clearInterval to stop checking when you have the data. An example usage of setInterval and clearInterval methods is [here](https://www.w3schools.com/jsref/met_win_clearinterval.asp) – ilkengin Oct 28 '20 at 08:49