一招实现angular8组件按需加载
最近在做一个记账的移动端小网页,用到了NG-ZORRO-MOBILE TabBar标签栏
,具体页面如下图:
这个组件3个tab都在同一个页面,这就导致以下问题
- 用户打开首页,记一笔和图表的tab数据也会被加载
- 用户没有打开的tab数据也加载会导致页面反应迟钝,影响体验
- 没有打开的tab后端也调用了数据库加载数据,高并发的情况影响后端数据库性能(虽然我的小网站没有高并发,哈哈哈)
TabBar标签栏核心代码
- 首页加载a组件
<app-a></app-a> - 记一笔加载b组件
<app-b></app-b> - 图表加载a组件
<app-c></app-c>
selectedIndex参数代表当前加载的tab索引,首页->记一笔->图表依次是 0->1->2
这样的话,我么可以通过判断当前索引是多少,来控制是否加载对应组件
具体控制代码
<div *ngIf="selectedIndex==1"><!-- 记一笔加载b组件--><app-b></app-b></div>
完整代码
<TabBar[hidden]="false"[barTintColor]="'white'"[tintColor]="'#108ee9'"[ngStyle]="tabbarStyle"[activeTab]="selectedIndex"[unselectedTintColor]="'#888'"[tabBarPosition]="'bottom'"[prerenderingSiblingsNumber]="0"(onPress)="tabBarTabOnPress($event)"><TabBarItem [title]="'首页'" [key]="1" [icon]="iconbasics" [selectedIcon]="iconbasicshow"><ng-template #iconbasics><div style="width:22px;height: 22px;background: url('./assets/img/icon/basics.png') center center / 21px 21px no-repeat;"></div></ng-template><ng-template #iconbasicshow><div style="width:22px;height: 22px;background: url('./assets/img/icon/basics_show.png') center center / 21px 21px no-repeat;"></div></ng-template><!-- 首页加载a组件--><app-a></app-a></TabBarItem><TabBarItem [title]="'记一笔'" [key]="2" [icon]="iconkeep" [selectedIcon]="iconkeepshow"><ng-template #iconkeep><div style="width:22px;height: 22px;background: url('./assets/img/icon/keep.png') center center / 21px 21px no-repeat;"></div></ng-template><ng-template #iconkeepshow><div style="width:22px;height: 22px;background: url('./assets/img/icon/keep_show.png') center center / 21px 21px no-repeat;"></div></ng-template><div *ngIf="selectedIndex==1"><!-- 记一笔加载b组件--><app-b></app-b></div></TabBarItem><TabBarItem [title]="'图表'" [key]="3" [icon]="icongraph" [selectedIcon]="icongraphshow"><ng-template #icongraph><div style="width:22px;height: 22px;background: url('./assets/img/icon/graph.png') center center / 21px 21px no-repeat;"></div></ng-template><ng-template #icongraphshow><div style="width:22px;height: 22px;background: url('./assets/img/icon/graph_show.png') center center / 21px 21px no-repeat;"></div></ng-template><div *ngIf="selectedIndex==2"><!-- 图表加载b组件--><app-c></app-c></div></TabBarItem></TabBar>