Is there a way to pass dynamic data to a component in Angular?

I am trying to pass data that is dynamic for a child component. But I always get the data as undefined in the child component. That's what I'm doing.

ParentComponent.ts

results: any[];
ngOnInit() {
this.http.get('url').subscribe(data => this.results = data);
}

ParentComponent.html

<app-childComponent [dataNeeded]=results></app-childComponent>

ChildComponent.ts

@Input('dataNeeded') dataNeeded: any[];
ngOnInit() {
 console.log(dataNeeded); //Always undefiend
}

So, as expected, it does not wait for an asynchronous call and returns me undefined. How to transfer dynamic data to a component?

+4
source share
4 answers

The problem is that the UI thread will display the child component before subscribing from the observable is complete.

you need to do it like this:

import { ChangeDetectorRef } from '@angular/core';

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

and in HTML you must first check the value.

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

, .markForCheck() , ", , ng-. , , , .

+2

OnChanges.

, :

ngOnChanges(changes) {
  if (changes['dataNeeded'] && this.dataNeeded) {
    console.log(this.dataNeeded);
  }
}

PS ChildComponent.ts, this:

ngOnInit() {
 console.log(this.dataNeeded);
}
+2

, data , :

html :

<app-childComponent [dataNeeded]="results"></app-childComponent>

in the child component, you check your changes Inputusing OnCh:

ngOnChanges(changes: SimpleChanges) {   
   for (let propName in changes) {
      // when your @Input value is changed  
      if(propName === "dataNeeded"){
          console.log(dataNeeded);
      }
   }
}

Hope this helps :)

0
source

Why not use Observable with an asynchronous channel. If you want to use the console log of this value, use the installer. The asynchronous pipe will also take care of unsubscribing.

results: Observable<any[]>;
ngOnInit() {
  this.results = this.http.get('url');
}

In HTML

<app-childComponent [dataNeeded]="results | async"></app-childComponent>

And in your child component

@Input('dataNeeded') 
set dataNeeded(val: any[]) {
  console.log(val);
}
0
source

Source: https://habr.com/ru/post/1690384/


All Articles