我有一个包含很少子组件的页面:
<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因为子组件不会被加载。
知道怎么做吗?
答案 0 :(得分:1)
如果属性allChildrenLoaded
表示子项已加载,则可以将其绑定到主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>
您可以使用@ViewChildren
和changes
的{{1}}事件来检测组件何时加载:
QueryList
在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
请参阅this stackblitz了解演示。