Angular按钮跳转登录页异常:点击闪烁且登录页显示在首页下方
解决方案
一、先解决页面闪烁问题
页面闪烁是因为你的<a>标签带了href="#",点击时会触发浏览器默认的锚点跳转行为,和Angular路由的router.navigate产生冲突。可以通过两种方式修复:
方式1:移除href="#"并阻止默认行为
修改myaccount-dropdown.html:
<a class="sub-menu-link" (click)="$event.preventDefault(); navigateToLogin('login')"> <button>Login</button> </a>
方式2:替换<a>标签为普通容器
如果不需要<a>标签的样式语义,直接用<div>包裹按钮:
<div class="sub-menu-link"> <button (click)="navigateToLogin('login')">Login</button> </div>
二、让登录页独立显示(不加载header/footer)
目前你的app.component.html是直接把header、footer和路由出口放在一起,导致所有路由页面都会被这两个组件包裹。可以通过两种方案实现登录页独立:
方案1:基于路由判断条件渲染header/footer
修改app.component.html,只在非登录路由下显示公共组件:
<app-header *ngIf="currentRoute !== 'login'"></app-header> <router-outlet></router-outlet> <app-footer *ngIf="currentRoute !== 'login'"></app-footer>
然后在app.component.ts中监听路由变化,获取当前路由:
import { Component } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; import { filter } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { currentRoute: string = ''; constructor(private router: Router) { this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe((event: NavigationEnd) => { // 截取路由路径(去掉开头的/) this.currentRoute = event.urlAfterRedirects.replace(/^\//, ''); }); } }
方案2:使用路由布局组件拆分(更推荐)
创建一个MainLayoutComponent作为带header/footer的公共布局:
- 新建
main-layout.component.html:
<app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer>
- 修改
app-routing.module.ts,将需要header/footer的路由作为布局组件的子路由,登录页作为顶级独立路由:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { MainLayoutComponent } from './main-layout/main-layout.component'; // 导入你的首页等需要公共布局的组件,比如HomeComponent const routes: Routes = [ { path: '', component: MainLayoutComponent, children: [ // 这里放所有需要header/footer的路由 { path: '', component: HomeComponent }, // 其他路由... ] }, // 登录页作为顶级路由,不使用公共布局 { path: 'login', component: LoginComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
这样登录页会直接渲染在根路由出口,不会包含header和footer,而其他页面会加载在布局组件的路由出口中,自动带上公共导航栏和页脚。
内容的提问来源于stack exchange,提问作者Farjana
相关产品推荐
相关产品推荐

