Reputation: 917
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 {
}
Upvotes: 10
Views: 16570
Reputation: 9240
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>
Upvotes: 13