Angular页面状态保留:如何避免链接点击重载实现标签式切换
Angular路由链接点击触发页面重载的解决方案
问题根源
当点击指向当前已激活路由的routerLink(比如当前已在根路径/,再点击routerLink="/"的链接),Angular默认会重新加载对应组件,导致页面状态丢失。你尝试用preventDefault()阻止默认行为,但这会同时阻止正常的路由跳转(当用户不在目标路由时),不是最优解。
最优解决方案:配置路由忽略同URL导航
在路由模块中添加onSameUrlNavigation: 'ignore'配置,让Angular忽略指向当前激活路由的导航请求,避免组件重载,同时保留你的自定义点击逻辑。
修改路由配置
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { MapsComponent } from './maps/maps.component'; import { ContactUsComponent } from './contact-us/contact-us.component'; import { TheCenterComponent } from './about/the-center/the-center.component'; import { PartnersComponent } from './about/partners/partners.component'; import { AbouUsComponent } from './about/abou-us/abou-us.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; import { TutorialsComponent } from './tutorials/tutorials.component'; @NgModule({ imports: [RouterModule.forRoot([ { path: '', component: MapsComponent }, { path: 'Dev', component: MapsComponent }, { path: 'map', component: MapsComponent }, { path: 'Contact', component: ContactUsComponent }, { path: 'Center', component: TheCenterComponent }, { path: "Partners", component: PartnersComponent }, { path: "About", component: AbouUsComponent }, { path: "Dev/Tutorial", component: TutorialsComponent }, { path: '**', component: PageNotFoundComponent } ], { onSameUrlNavigation: 'ignore' // 新增此配置 })], exports: [RouterModule] }) export class AppRoutingModule { }
恢复原链接与函数(可选)
配置完成后,你可以恢复原来的链接和map()函数,无需再用preventDefault():
<a class="a flex-item-c" (click)="map()" [ngClass]="{'butin':!map, 'buttout':map}" [routerLink]="['/']" [queryParamsHandling]="'preserve'">{{ 'nav.map' | translate }}</a>
map() { this.navDesign = true; this.myRef.current.contentWindow.execCommand('map'); this.showSo = false; this.showKi = false; this.showPe = false; this.showLo = false; this.map = true; this.conta = false; this.aboutUs = false; this.partners = false; this.theCenter = false; }
备选方案:手动判断路由状态
如果不想修改全局路由配置,可以在点击事件中判断当前路由,仅在已处于目标路由时阻止默认行为:
注入Router服务
在组件构造函数中注入Router:
import { Router } from '@angular/router'; constructor(private router: Router) {}
修改点击函数
mapF(event) { // 判断当前是否已在根路由 if (this.router.url === '/') { event.preventDefault(); // 阻止重载 } // 执行自定义逻辑 this.navDesign = true; this.myRef.current.contentWindow.execCommand('map'); this.showSo = false; this.showKi = false; this.showPe = false; this.showLo = false; this.map = true; this.conta = false; this.aboutUs = false; this.partners = false; this.theCenter = false; }
备选方案:移除routerLink,纯手动逻辑
如果该链接仅用于切换状态(不需要路由跳转),可以直接去掉routerLink,仅保留点击事件:
<a class="a flex-item-c" (click)="map()" [ngClass]="{'butin':!map, 'buttout':map}">{{ 'nav.map' | translate }}</a>
函数保持原逻辑即可,无需处理事件对象。
内容的提问来源于stack exchange,提问作者otacksverflow
相关产品推荐
相关产品推荐

