Angular 5中如何通过按钮点击事件实现routerLink路由跳转
Hey there! Nice to see you already have a handle on using routerLink with anchor tags—let’s break down how to get that same routing behavior working when clicking a button in Angular 5. You’ve got two solid options depending on whether you need to add extra logic before navigating:
Option 1: Use routerLink Directly on the Button
The simplest approach is that Angular’s routerLink directive isn’t just limited to <a> tags—it works with any clickable element, including buttons! You can use it exactly like you did with your anchor tag:
<button class="nav-item nav-link-edit" [routerLink]="['']">Home</button>
This will trigger the same navigation to your Home component as your original <a> tag, no extra code needed. It’s clean and straightforward for cases where you don’t need to run any logic before the navigation.
Option 2: Use the Router Service with a Click Event
If you need to perform some pre-navigation logic (like form validation, saving user input, or checking permissions), you’ll want to use Angular’s Router service. Here’s how to set that up:
- Import the Router service in your component:
import { Router } from '@angular/router';
- Inject the Router via your component’s constructor:
constructor(private router: Router) { }
- Create a method to handle the navigation:
navigateToHome(): void { // Add your custom logic here (e.g., validate form, save data) console.log('Preparing to navigate to Home...'); // Navigate to the Home component using the same path as your routerLink this.router.navigate(['']); }
- Bind the method to your button’s click event:
<button class="nav-item nav-link-edit" (click)="navigateToHome()">Home</button>
This gives you full control over what happens before the navigation takes place, making it perfect for more complex workflows.
内容的提问来源于stack exchange,提问作者dilusha_dasanayaka

