Sharing Top Content from the Angular-sphere.

3 Ways to Pass Async Data to Angular 2+ Child Components ― Scotch

3 Ways to Pass Async Data to Angular 2+ Child Components

☞ 

#Angular2

  • // blogger.component.ts – – import { Component, OnInit, Input } from ‘@angular/core’; – import { Http } from ‘@angular/http’; – import { Post } from selector: ‘bloggers’, – template: ` – h1Posts by: {{ blogger }}/h1 – div – posts [data]=”posts”/posts – /div – ` – }) – export class…
  • // posts.component.ts – – import { Component, Input, OnChanges, OnInit, SimpleChanges } from ‘@angular/core’; – import { BehaviorSubject } from ‘rxjs/BehaviorSubject’; – import { Post, GroupPosts } from selector: ‘posts’, – template: ` – div class=”list-group” – div *ngFor=”let group of groupPosts” class=”list-group-item” – h4{{ group.category }}/h4 – ul -…
  • Our blogger component: – – // blogger.component.ts – – … – template: ` – h1Posts by: {{ blogger }}/h1 – div *ngIf=”posts” – posts [data]=”posts”/posts – /div – ` – … – Our posts component.
  • // blogger.component.ts – – … – template: ` – h1Posts by: {{ blogger }}/h1 – div – posts [data]=”posts”/posts – /div – ` – … – Our posts component – – // posts.component.ts – – … – ngOnChanges(changes: SimpleChanges) { – // only run when property “data” changed – if…
  • Please revert all the changes in previous solution – – There are no changes in our blogger component: – – // blogger.component.ts – – … – template: ` – h1Posts by: {{ blogger }}/h1 – div – posts [data]=”posts”/posts – /div – ` – … – Let’s update our post…

Let’s start with a common use case. You have some data you get from external source (e.g. by calling API). You want to display it on screen.

However, instead of displaying it on the same component, you would like to pass the data to a child component to display.

The child component might has some logic to pre-process the data before showing on screen.

Our Example

For example, you have a blogger component that will display blogger details and her posts. Blogger component will gets the list of posts from API.

Instead of writing the logic of displaying the posts in the blogger component, you want to reuse the posts component that is created by your teammate, what you need to do is pass it the posts data.

The posts component will then group the posts by category and display accordingly, like this:

Isn’t That Easy?

It might look easy at the first glance. Most of the time we will initiate all the process during our component initialization time – during ngOnInit life cycle hook (refer here for more details on component life cycle hook).

In our case, you might think that we should run the post grouping logic during ngOnInit of…

3 Ways to Pass Async Data to Angular 2+ Child Components ― Scotch