Компонент @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
});

}

но при попытке вызвать данные асинхронной переменной вернуть undefind

Что я могу сделать, чтобы решить эту проблему?

1 ответ

В дочернем компоненте вы можете определить событие для уведомления родителя об изменении данных, как показано ниже.

@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);
        });
    }
}
Другие вопросы по тегам