angularangular-dynamic-components

How to wait for NgOnInit to complete inside Angular Dynamic Component?


I am trying to set reactive form controls inside dynamic component from parent component.

@ViewChild("priceSpecComp", { read: ViewContainerRef}) priceSpecComp: ViewContainerRef

LoadDynamicComponent(variant, addons) {
    priceSpecComp.clear();
    var comp = priceSpecComp.createComponent(PricingSpecDynamicComponent)
    comp.instance.setFormControls(variant, addons);
}

Inside PricingSpecDynamicComponent NgOnInit there is a http call which retrieves information from server to load some dropdowns with available information.

Problem i am getting right now is that when i am calling setFormControls(variant, addons) in created instance of dynamic component form with dropdowns is not loaded yet, since NgOnInit is not completed.

Are there any way to wait for NgOnInit to finish or am i missing something very simple here?


Solution

  • You can use other lifecycle hooks such as ngAfterViewInit(){}. As the name stating, it gets executed after the initialization of the view. You can explore other convenient hooks similar to OnInit and AfterViewInit depending on your needs in the link above. The other option I can think of is to transform the Observable (The http callback) into a promise and then use async ... await.

    PS: I do not recommend promise based methods in Angular. Observables are the way to go and they are more native with RxJS under the hood.