Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, wait for one component to render completely before rendering the other

I have an angular component which in turn has two more components in it, I want to make sure that second-component loads/renders only after the first-component is rendered completely, how can I achieve it?

combined.component.html

<first-component></first-component>
<second-component></second-component>

combined.component.ts

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

@Component({
    selector: 'main-component',
    templateUrl: './combined.component.html',
    styleUrls: ['./combined.component.css']
})
export class CombimedComponent {

}
like image 208
Nikhil Bharadwaj Avatar asked Aug 06 '19 04:08

Nikhil Bharadwaj


People also ask

What is the best way to load data before rendering the component?

It's preferable to pre-fetch data from the server so it's ready the moment the route is activated. This also allows you to handle errors before routing to the component.

Does ngOnInit run before render?

The component gets rendered before the API call in the ngOnInit function is done fetching the data.

Where should initial data fetching in an angular component occur?

An ngOnInit() is a good place for a component to fetch its initial data.

What is render component in angular?

Angular gives us the mechanism to render components dynamically through View Container using ComponentFactory. To do this, we need to know the Component Type at the compile time. The most dynamic component rendering mechanism would be the one where we don't know what component will be rendered at the compile time.


1 Answers

An easy way to do it would be...

In your first child component add an EventEmitter that fires an event after it has been completely loaded like so

first-component.component.ts

import { Component, Output, EventEmitter, AfterViewChecked } from 'angular/core';

// ...

@Output() finishedLoading: EventEmitter<boolean> = new EventEmitter<boolean>();

ngAfterViewChecked() {
   // you could also do this after a service call of some sort
   this.finishedLoading.emit(true);
}

ngAfterViewChecked is the last lifecycle hook run on a component, so at this point the component has been completely loaded!

You can learn more about lifecycle hooks here

Then in your parent container you can set a flag called hasLoaded

combined.component.ts

// ...

hasLoaded: boolean = false;

then in your parents component html you can listen for the finishedLoading event and then render your second component like so..

combined.component.ts

<!-- Listens for the finishedLoading event and then sets hasLoaded once its been fired -->
<first-component (finishedLoading)="hasLoaded = $event"></first-component>

<!-- Doesnt render the second component until hasLoaded has been set to true -->
<second-component *ngIf="hasLoaded"></second-component>
like image 74
Smokey Dawson Avatar answered Oct 02 '22 11:10

Smokey Dawson