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 {
}
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.
The component gets rendered before the API call in the ngOnInit function is done fetching the data.
An ngOnInit() is a good place for a component to fetch its initial data.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With