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

Angular按钮元素出现Can't bind to 'routerLink'错误,如何实现跳转?

解决方法

1. 确保组件所属模块导入RouterModule

你的EmployeesComponent如果是声明在AppModule或其他功能模块中,必须保证该模块的imports数组包含RouterModule:

以AppModule为例:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeesComponent } from './employees/employees.component';
import { EmployeeByIdComponent } from './employee-by-id/employee-by-id.component';

@NgModule({
  declarations: [
    AppComponent,
    EmployeesComponent,
    EmployeeByIdComponent
  ],
  imports: [
    BrowserModule,
    RouterModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2. 独立组件需在@Component中添加RouterLink导入

如果你的EmployeesComponent是独立组件(即@Component中设置了standalone: true),要在组件的imports数组里引入RouterLink:

修改employees.component.ts:

import { Component, OnInit } from '@angular/core';
import { RouterLink } from '@angular/router';
import { DataService } from 'src/app/service/data.service';

@Component({
  selector: 'app-employees',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css'],
  standalone: true,
  imports: [RouterLink]
})
export class EmployeesComponent implements OnInit {
  employee:any;

  constructor(private dataService:DataService) {}

  ngOnInit(): void {
    this.getEmployeesData();
  }

  getEmployeesData() {
    this.dataService.getData().subscribe(res => {
      this.employee = res;
    });
  }
}

3. 优化routerLink写法(可选)

推荐使用属性绑定方式编写routerLink,比字符串拼接更规范且能自动处理参数编码:

<td>
  <button class="btn btn-warning btn-sm mx-2" [routerLink]="['employee', emp.id]">View Data</button>
</td>

内容的提问来源于stack exchange,提问作者Narakaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:42:33