0

I have a list of buttons that route to various links:

<li nz-menu-item [nzSelected]="isSelected('/home')" routerLink="/home" routerLinkActive="active">
  <span title><i nz-icon type="home"></i>Home</span>
</li>
<li nz-menu-item [nzSelected]="isSelected('/news')" routerLink="/news" routerLinkActive="active">
  <span title><i nz-icon type="info"></i>News</span>
</li>

I use the directive [nzSelected] and function:

isSelected(route: string): boolean {
  return route === this.router.url;
}

to highlight the button to the currently opened route. I have noticed a problem - this makes performance worse, because on each route change, the method 'isSelected' is launched more than 100 times.

What would be the best solution to avoid method execution so much times on each page change?

4

2 回答 2

1

来自RouterLinkActive指令的文档:

允许您在链接的路由变为活动状态时向元素添加 CSS 类。

这基本上就是你正在做的事情[nzSelected]="isSelected('/home')"

routerLinkActive为您开箱即用。摆脱[nzSelected]="isSelected('...')"你应该就好了

<li
  nz-menu-item 
  routerLink="/home" 
  routerLinkActive="active">
  <span title><i nz-icon type="home"></i>Home</span>
</li>
<li 
  nz-menu-item
  routerLink="/news" 
  routerLinkActive="active">
  <span title><i nz-icon type="info"></i>News</span>
</li>

PS:我写了一篇关于 Angular Apps 性能改进的Medium 文章。虽然它主要专注于 Angular Reactive 表单,但性能改进技术仍然相当多。您可能想在这里查看

于 2019-06-20T13:40:50.497 回答
1

如果您isSelectedrouterLinkActive.

试试这个:

<li nz-menu-item [nzSelected]="homeRla?.isActive" routerLink="/home" routerLinkActive="active" #homeRla="routerLinkActive">

并回答你,可以使用

changeDetectionStrategy: ChangeDetectionStrategy.onPush

在您的组件装饰器中,将更改检测限制在希望它运行的时间。

于 2019-06-20T13:18:58.760 回答