Angular 2中如何通过下拉列表选项实现页面路由跳转
Got it, the problem here is that <option> tags don't work with Angular's routerLink directive directly—they're purely form elements, not designed to trigger navigation on their own. Let's fix this with a straightforward, Angular-friendly approach:
Step 1: Update the Template
First, modify your select element to add a (change) event handler, and give the "Add New" option a distinct value so we can easily identify it later:
<select class="form-control" id="category" required [(ngModel)]="model.category" name="category" #category="ngModel" (change)="handleCategorySelection($event)"> <option disabled>None</option> <option value="add-new-option">Add New</option> <option *ngFor="let i of data1" [value]="i.id">{{i.category}}</option> </select>
Step 2: Add Navigation Logic in the Component
Next, inject Angular's Router service into your component, then implement the handleCategorySelection method to check the selected value and trigger navigation when needed:
import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ // Your component metadata (selector, templateUrl, etc.) }) export class YourComponent { model: any = {}; // Your existing model object data1: any[] = []; // Your existing data array constructor(private router: Router) {} handleCategorySelection(event: Event) { const selectedValue = (event.target as HTMLSelectElement).value; // Check if the user selected "Add New" if (selectedValue === 'add-new-option') { // Navigate to your target route this.router.navigate(['/pages/products/dashboard']); // Optional: Reset the select to its default state after navigation this.model.category = null; } } }
Why This Works
- The
(change)event fires every time the user selects a new option, letting us capture the selected value. - Using Angular's
Routerservice is the standard way to trigger navigation programmatically in components, which avoids the limitation of<option>tags not supportingrouterLink. - Giving "Add New" a unique value (like
add-new-option) ensures we don't conflict with theidvalues from yourdata1array.
Quick Notes
- Make sure you've imported the
RouterModulein your app module and set up the target route (/pages/products/dashboard) correctly. - If you want to prevent the "Add New" value from being bound to
model.category, you can skip the[(ngModel)]binding for that specific option, but the above approach works fine since we reset the model after navigation if needed.
内容的提问来源于stack exchange,提问作者Sudharsan Venkatraj
相关产品推荐
相关产品推荐

