当前位置: 动力学知识库 > 问答 > 编程问答 >

angular2 - Redisplaying the results of an angular 2 component elsewhere in the DOM

问题描述:

I have an Angular 2 component that makes db calls to render its results, like

<div class="row flex-items-xs-middle flex-items-xs-center" *ngFor="let step of steps; let i = index">

stuff here....

<mydbresults [ref]="step._id"></mydbresults>

more stuff here....

</div>

is a component that is being given an _id ref by my steps array in my parent class / component. has an '@Input() ref which is used to make a REST call to pull some json and render it with its template.

This works fine and I get my results for each step. Now I would like to show the collective set of elsewhere in the DOM outside of the *ngFor loop.

<summary>

all my db results here...

</summary>

I could write a component that essentially renders all the steps but since I already have fetched the results I would rather not have to make calls to the db again if I already have the results in my DOM elsewhere.

How can I re-render the results of all the components rendered in the *ngFor elsewhere in the DOM?

网友答案:

Have your myDbResults component output the result of the db call, e.g.

//Use this to output the result after your API call returned from the database.
@Output() 
private onDbResultFetched = new EventEmitter();

Have your parent component listen for this event, collect all the results and then pass it down via an input property to the summary component.

Optionally you could emit another event from the myDbResults component that signals the parent component that ALL of the API calls have been made, so that the parent component can only start processing the results once this is done.

If you also want to reuse the markup of the result, create a new component that is essentially a stateless component that takes the result of the API call as input and with the markup of your myDbResults component. Have myDbResults as well as summary use that component.

分享给朋友:
您可能感兴趣的文章:
随机阅读: