有什么方法可以将动态数据传递给Angular中的组件? [英] Is there any way I can pass dynamic data to a component in Angular?
问题描述
我正在尝试将动态数据传递给子组件.但是我总是在子组件中获得未定义的数据.下面是我在做什么.
I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.
ParentComponent.ts
ParentComponent.ts
results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}
ParentComponent.html
ParentComponent.html
<app-childComponent [dataNeeded]=results></app-childComponent>
ChildComponent.ts
ChildComponent.ts
@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
console.log(dataNeeded); //Always undefiend
}
因此,正如预期的那样,它不会等待异步调用,并且会返回未定义的状态.如何将动态数据传递给组件?
So as expected, it doesn't wait for the asynchronous call and returns me undefined. How do i pass the dynamic data to the component?
推荐答案
问题是UI线程将在可观察的订阅完成之前呈现子组件.
The problem is that the UI thread will render the child component before the subscribe from the observable finished.
您需要这样做:
import { ChangeDetectorRef } from '@angular/core';
constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
this.http.get('url').subscribe(data => {
this.results = data;
this.ref.markForCheck();
});
}
,并且必须先在HTML中测试该值.
and in the HTML you have to test the value first.
<ng-container *ngIf="results != null">
<app-childComponent [dataNeeded]=results></app-childComponent>
</ng-container>
稍作说明, .markForCheck()
将在订阅后刷新结果并将通知所有正在使用此值"更新其值的组件,包括ng-container.容器现在允许渲染子组件,这将保证当子组件将经历其生命周期时结果不会为null.
A little description, the .markForCheck()
will refresh the result after the subscribe and will inform all the components which are using this "value" to update its value, including the ng-container. The container would allow rendering the child component now, which will guarantee that the results are not null when the child will be going through its life cycle.
这篇关于有什么方法可以将动态数据传递给Angular中的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!