最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular, wait for one component to render completely before rendering the other - Stack Overflow

programmeradmin24浏览0评论

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

binedponent.html

<first-ponent></first-ponent>
<second-ponent></second-ponent>

binedponent.ts

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

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

}

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

bined.ponent.html

<first-ponent></first-ponent>
<second-ponent></second-ponent>

bined.ponent.ts

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

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

}
Share Improve this question asked Aug 6, 2019 at 4:03 Nikhil BharadwajNikhil Bharadwaj 9175 gold badges26 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

An easy way to do it would be...

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

first-ponent.ponent.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 ponent, so at this point the ponent has been pletely loaded!

You can learn more about lifecycle hooks here

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

bined.ponent.ts

// ...

hasLoaded: boolean = false;

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

bined.ponent.ts

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

<!-- Doesnt render the second ponent until hasLoaded has been set to true -->
<second-ponent *ngIf="hasLoaded"></second-ponent>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论