You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular导航栏添加[routerLink]后触发DOMException错误求助

问题原因及修复方案

错误根源

你代码里的[class="home-link"]写法不符合Angular的绑定规范,这种写法会导致浏览器尝试设置一个名为[class的无效属性,直接触发DOMException错误。

修复代码

根据需求选择以下两种正确写法之一:

  1. 静态样式(无需动态切换):直接使用普通class属性,不需要方括号绑定
<nav>
  <li class="navbar-list">
    <a [routerLink="/home-component"] class="home-link">Home</a>
    <a [routerLink="/about.component"] class="about-link">About</a>
  </li>
</nav>
<router-outlet></router-outlet>
  1. 动态样式(需根据条件切换):使用Angular专属的[class.类名]语法绑定布尔值控制样式显示
<!-- 示例:通过组件内的isHomeActive变量控制类名生效 -->
<a [routerLink="/home-component"] [class.home-link]="isHomeActive">Home</a>

(注:isHomeActive需要在navbar.component.ts中定义为布尔类型变量)

额外必要检查

  • 确保app-routing.module.ts中已正确注册路由:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: 'home-component', component: HomeComponent },
  { path: 'about.component', component: AboutComponent },
  { path: '', redirectTo: '/home-component', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  • 确认AppModule中已导入RouterModule和AppRoutingModule,且NavbarComponent已被正确声明。

内容的提问来源于stack exchange,提问作者ΔβΙΧΚαΓ K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:54:24