一招实现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
这样的话,我么可以通过判断当前索引是多少,来控制是否加载对应组件

具体控制代码
  1. <div *ngIf="selectedIndex==1">
  2. <!-- 记一笔加载b组件-->
  3. <app-b></app-b>
  4. </div>
完整代码
  1. <TabBar
  2. [hidden]="false"
  3. [barTintColor]="'white'"
  4. [tintColor]="'#108ee9'"
  5. [ngStyle]="tabbarStyle"
  6. [activeTab]="selectedIndex"
  7. [unselectedTintColor]="'#888'"
  8. [tabBarPosition]="'bottom'"
  9. [prerenderingSiblingsNumber]="0"
  10. (onPress)="tabBarTabOnPress($event)">
  11. <TabBarItem [title]="'首页'" [key]="1" [icon]="iconbasics" [selectedIcon]="iconbasicshow">
  12. <ng-template #iconbasics>
  13. <div style="width:22px;height: 22px;background: url('./assets/img/icon/basics.png') center center / 21px 21px no-repeat;"></div>
  14. </ng-template>
  15. <ng-template #iconbasicshow>
  16. <div style="width:22px;height: 22px;background: url('./assets/img/icon/basics_show.png') center center / 21px 21px no-repeat;"></div>
  17. </ng-template>
  18. <!-- 首页加载a组件-->
  19. <app-a></app-a>
  20. </TabBarItem>
  21. <TabBarItem [title]="'记一笔'" [key]="2" [icon]="iconkeep" [selectedIcon]="iconkeepshow">
  22. <ng-template #iconkeep>
  23. <div style="width:22px;height: 22px;background: url('./assets/img/icon/keep.png') center center / 21px 21px no-repeat;"></div>
  24. </ng-template>
  25. <ng-template #iconkeepshow>
  26. <div style="width:22px;height: 22px;background: url('./assets/img/icon/keep_show.png') center center / 21px 21px no-repeat;"></div>
  27. </ng-template>
  28. <div *ngIf="selectedIndex==1">
  29. <!-- 记一笔加载b组件-->
  30. <app-b></app-b>
  31. </div>
  32. </TabBarItem>
  33. <TabBarItem [title]="'图表'" [key]="3" [icon]="icongraph" [selectedIcon]="icongraphshow">
  34. <ng-template #icongraph>
  35. <div style="width:22px;height: 22px;background: url('./assets/img/icon/graph.png') center center / 21px 21px no-repeat;"></div>
  36. </ng-template>
  37. <ng-template #icongraphshow>
  38. <div style="width:22px;height: 22px;background: url('./assets/img/icon/graph_show.png') center center / 21px 21px no-repeat;"></div>
  39. </ng-template>
  40. <div *ngIf="selectedIndex==2">
  41. <!-- 图表加载b组件-->
  42. <app-c></app-c>
  43. </div>
  44. </TabBarItem>
  45. </TabBar>