如何让Angular 2多选下拉框选中的选项变为可点击链接?
Hey there! I get that you want your selected items in the Angular 2 multiselect component to show up as clickable links—let's walk through how to make that happen, regardless of which multiselect library you're using (I'll cover the most common ones to keep it flexible):
1. 自定义选中项的模板渲染
Nearly all popular Angular multiselect libraries support custom templates for rendering selected items. Let's use ng-select as an example first—you can override the selected item display with an ng-template:
<ng-select [items]="options" [(ngModel)]="selectedItems" multiple="true"> <!-- Custom template for selected items --> <ng-template ng-template="selectedItem" let-item="item"> <a href="javascript:void(0)" (click)="handleItemClick(item)">{{ item.label }}</a> </ng-template> <!-- Optional: Keep default dropdown option styling --> <ng-template ng-template="item" let-item="item"> <span>{{ item.label }}</span> </ng-template> </ng-select>
2. Add a click handler in your component class
Next, define the click logic in your component's TypeScript file to handle what happens when someone clicks the link:
import { Component } from '@angular/core'; // Uncomment below if you need routing // import { Router } from '@angular/router'; @Component({ selector: 'app-multiselect-links', templateUrl: './multiselect-links.component.html' }) export class MultiselectLinksComponent { options = [ { id: 1, label: 'Project Alpha' }, { id: 2, label: 'Project Beta' }, { id: 3, label: 'Project Gamma' } ]; selectedItems: any[] = []; // Inject Router if you need navigation // constructor(private router: Router) {} handleItemClick(item: any) { // Replace this with your actual logic console.log(`You clicked on ${item.label} (ID: ${item.id})`); // Example: Navigate to a detail page // this.router.navigate(['/project-details', item.id]); } }
3. 适配Angular Material的mat-select
If you're using Angular Material's multiselect, use mat-select-trigger to customize the selected items display:
<mat-select [(ngModel)]="selectedItems" multiple> <mat-select-trigger> <div *ngFor="let item of selectedItems; let last = last"> <a href="javascript:void(0)" (click)="handleItemClick(item)">{{ item.label }}</a> <span *ngIf="!last">, </span> </div> </mat-select-trigger> <mat-option *ngFor="let option of options" [value]="option"> {{ option.label }} </mat-option> </mat-select>
4. Optional: Tweak the styling
Make the links look natural with a bit of CSS:
a { color: #1976d2; /* Use your project's theme color */ text-decoration: underline; cursor: pointer; margin-right: 4px; } a:hover { color: #0d47a1; }
Quick Notes
- Double-check your library's docs for template syntax (some might use different directives like
ng-templatevsng-container) - Use
javascript:void(0)to prevent unwanted page jumps unless you intend to link to an external URL - If you need routing, don't forget to inject the
Routerservice and usenavigate()
内容的提问来源于stack exchange,提问作者sonu gupta

