gpt4 book ai didi

angular - 如何仅在 Angular 5 中所有子项都已完全加载时才显示页面?

转载 作者:太空狗 更新时间:2023-10-29 19:26:07 26 4
gpt4 key购买 nike

我有一个包含几个子组件的页面:

<div class="wrapper" *ngIf="isPageFullyLoaded">

<header></header>

<main class="content">
<trip-list></trip-list>
</main>

<footer></footer>
</div>

ts文件包括以下内容:

...
public isPageFullyLoaded = false;
...
ngAfterContentInit() {
this.isPageFullyLoaded = true;
}

The child trips-list:
<section *ngIf="trips">
<ul>
<li *ngFor="let data of trips" >
...

使用 rest api 加载行程列表:

getTrips() {
this.fundService.getTrips().subscribe(
data => { this.trips= data; },
err => console.error(err),
() => console.log(this.trips)
);
}

我也尝试过 ngAfterViewInit

我需要一种方法来仅在子项完全加载时显示主 div。我不能在 div 中使用 *ngIf,因为子组件不会加载。

知道怎么做吗?

最佳答案

如果属性 allChildrenLoaded 表示子项已加载,您可以将其绑定(bind)到主 div 的 hidden 属性。与仅在满足条件时才加载元素的 ngIf 相反,hidden 属性隐藏了实际存在于 DOM 中的元素。

<div class="wrapper" [hidden]="!allChildrenLoaded">
<child1></child1>
<child2 *ngFor="let value of values"></child2>
<trip-list (loaded)="onTripListLoaded()"></trip-list>
</div>

您可以使用 @ViewChildrenQueryListchanges 事件来检测何时加载组件:

export class ParentComponent implements AfterViewInit {

@ViewChildren(Child1Component) children1: QueryList<Child1Component>;
@ViewChildren(Child2Component) children2: QueryList<Child2Component>;

private child1Loaded = false;
private children2Loaded = false;
private tripListLoaded = false;

private expectedChildren2Count = 5; // Expected number of Child2Component to be loaded

constructor(private cd: ChangeDetectorRef) { }

ngAfterViewInit() {
this.child1Loaded = this.children1.length > 0;
this.children2Loaded = this.children2.length === expectedChildren2Count;
this.cd.detectChanges(); // To avoid possible runtime error

this.children1.changes.subscribe(() => {
this.child1Loaded = this.children1.length > 0;
});
this.children2.changes.subscribe(() => {
this.children2Loaded = this.children2.length === expectedChildren2Count;
});
}

onTripListLoaded() {
this.tripListLoaded = true;
}

get allChildrenLoaded(): boolean {
return this.child1Loaded && this.child2Loaded && this.tripListLoaded;
}
}

trip-list 组件中,您可以在加载内容时发出 loaded 事件。父组件使用事件绑定(bind)来处理该事件(请参阅上面的标记)。

@Output() public loaded: EventEmitter<any> = new EventEmitter();

getTrips() {
this.fundService.getTrips().subscribe(
data => {
this.trips= data;
this.loaded.emit();
},
err => console.error(err),
() => console.log(this.trips)
);
}

参见 this stackblitz用于演示。

关于angular - 如何仅在 Angular 5 中所有子项都已完全加载时才显示页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190105/

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