ADVERTISEMENTS

How to pass dynamic data to a component in angular

Himanshu BatraOct 01, 2020
How to pass dynamic data to a component in angular

As we know that these days angular is most powerful frontend framework for web application. But for making web application successful, we need to load or fetch dynamic data according to user's request or inputs.

For retrieving data, we need to call a rest api which will return output and here we are going to elaborate passing that dynamic output to child component. For this we need to pass data before rendering to child component.

ADVERTISEMENTS

ChildComponent.ts

// Import change detection functionality from angular core.
import { ChangeDetectorRef } from '@angular/core';

// Initiate constructor 
constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
   this.http.get('api_url').subscribe(data => { 
     this.results = data;
     this.ref.markForCheck();
   });
}

markForCheck() will refresh the result and it will inform to all components ( which are using this ) to update its value. Now, we have to pass that dynamic data to child component through an attribute in html file .

ADVERTISEMENTS

ParentComponent.html

<ng-container *ngIf="results != null">
    <app-childComponent [dataNeeded]=results></app-childComponent>
</ng-container>

Now, we are ready with dynamic data to child component in angular.

ADVERTISEMENTS