gpt4 book ai didi

javascript - Angular,在渲染另一个组件之前等待一个组件完全渲染

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:49 26 4
gpt4 key购买 nike

我有一个 Angular 组件,它又包含两个组件,我想确保第二个组件仅在第一个组件完全渲染后才加载/渲染,我该如何实现?

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 {

}

最佳答案

一个简单的方法是...

在您的第一个子组件中添加一个 EventEmitter,它会在事件完全加载后触发一个事件,如下所示

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 是在组件上运行的最后一个生命周期钩子(Hook),因此此时组件已完全加载!

您可以了解有关生命周期 Hook 的更多信息 here

然后在您的父容器中,您可以设置一个名为 hasLoaded

的标志

combined.component.ts

// ...

hasLoaded: boolean = false;

然后在您的父组件 html 中,您可以监听 finishedLoading 事件,然后像这样呈现您的第二个组件..

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>

关于javascript - Angular,在渲染另一个组件之前等待一个组件完全渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com