Angular 12路由hash不匹配:点击href=#链接跳转首页如何解决
问题原因
Angular默认使用HTML5路由模式(无#前缀的路径),点击
href="#"的链接时,浏览器会默认将URL修改为当前域名加#,Angular路由识别到URL变化后会尝试匹配路由规则,若匹配不到就会触发重定向逻辑。
解决方案
方案1:全局拦截href="#"链接的默认行为(推荐,无需逐个修改现有链接)
在项目根组件(通常为app.component.ts)中添加全局点击监听,统一拦截所有href="#"的a标签点击事件,阻止默认跳转逻辑,对现有代码侵入性最小:
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { @HostListener('click', ['$event']) onGlobalClick(event: MouseEvent) { const targetEl = event.target as HTMLElement; const aTag = targetEl.closest('a'); if (aTag?.getAttribute('href') === '#') { event.preventDefault(); } } }
方案2:逐个修改链接属性(适合链接数量少的场景)
将所有href="#"的链接替换为以下任意一种写法即可:
- 替换属性为
href="javascript:void(0)",完全屏蔽默认跳转行为 - 使用Angular原生
routerLink指令:<a routerLink="" fragment="">链接文本</a> - 给链接添加点击事件阻止默认行为:
<a href="#" (click)="$event.preventDefault()">链接文本</a>
方案3:路由规则特殊匹配(零页面修改)
如果不方便修改页面代码,可以在路由数组最顶部添加自定义匹配规则,拦截空锚点的导航请求:
const routes: Routes = [ // 新增规则放在所有路由最前面 { matcher: (url) => { if (url.length === 0 && window.location.hash === '#') { return { consumed: url }; } return null; }, children: [] }, // 原有路由保持不变 { path: '', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'login', component: LoginComponent, canActivate: [LoggedInAuthGuard] }, { path: 'register', component: RagisterComponent, canActivate: [LoggedInAuthGuard] }, { path: 'pagenotfound', component: PagenotfoundComponent }, { path: '404', component: PagenotfoundComponent }, { path: 'profile', component: ProfileComponent }, { path: '**', redirectTo: '/404' }, ];
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

