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

前端 未结 4 1886
抹茶落季
抹茶落季 2021-01-12 20:42

I am trying to pass data that is dynamic to a child component. But I always get the data as undefined in the child component. Below is what I am doing.

ParentComp

4条回答
  •  一个人的身影
    2021-01-12 21:23

    The problem is that the UI thread will render the child component before the subscribe from the observable finished.

    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 the HTML you have to test the value first.

    
        
    
    

    A little description, the .markForCheck() will refresh the result after the subscribe and will inform all the components which are using this "value" to update its value, including the ng-container. The container would allow rendering the child component now, which will guarantee that the results are not null when the child will be going through its life cycle.

提交回复
热议问题