0
votes

I have an Angular 5 app which just renders a component

export class AppComponent {
    @ViewChild(TestComponent) testElement: Testcomponent;
}

But this child component needs some infos (e.g. there is config for additional created subcomponents) The config is loaded from an external source (rest), so i have created an http.get request and wrapped it in an rxjs Observable

In my AppComponent I have therefor a Observable<string> where i can subscribe to. My TestComponent basically is not able to show anything before the config is available - so my question is how I can wait with the initialization/rendering of the component until the Rest-Response is available?

2

2 Answers

1
votes

You can use *ngIf Directive to instantiate the child-component after the subscription is resolved or when data is Available.

Component-1

 public response$:Observable<Idata[]>;
    constructor(public service:ShareService)
      {
          this.response$= this.service.getdata();

      }

Component-1 Template

<ng-container *ngIf="response$">
<hello [response]="response$"></hello>
</ng-container>

Component-2

export class HelloComponent  {
@Input() response:Observable<Idata[]>


}

Component-2 Template

<div *ngFor="let item of (response|async)">
  {{item.body}}
<div>

LIVE DEMO

0
votes

You can do this by tapping in to the life cycle hook OnInit and having the child component take inputs with the async pipe.

Example

// parent component
export class MyParent implements OnInit {
  myObservable$: Observable<any>;
  ngOnInit() {
    //do whatever you need to get observable.
  }
}
//parent html
<my-child [data]="myObservable$ | async"></my-child>

//child component
export class MyChild {
  @Input() data: //whatever data type it is
  // do stuff
}