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
相关产品推荐
相关产品推荐

