public ngAfterViewInit() { this" /> public ngAfterViewInit() { this" /> public ngAfterViewInit() { this"/>

@ViewChild component undefined when trying to call async variable

448 Views Asked by At

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?

1

There are 1 best solutions below

2
ilkengin On

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