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

如何为Angular Material循环渲染的下拉框添加不重复值验证

Alright, let's fix that duplicate selection issue for your Angular Material dropdowns rendered with *ngFor. Here's how you can add the validation logic step by step, tailored to your existing template-driven setup:

1. Add Validation Logic to Your Component

First, we'll create a helper method to check for duplicate route selections, and optionally add logic to block invalid selections:

import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar'; // Optional, for user notifications

@Component({
  selector: 'app-route-selector',
  templateUrl: './route-selector.component.html',
  styleUrls: ['./route-selector.component.css']
})
export class RouteSelectorComponent {
  routemodeArray: any[] = [/* Your existing array data here */];
  getallRoutes: any[] = [/* Your full route list here */];

  constructor(private snackBar: MatSnackBar) {} // Optional

  routeCheck(routeId: number, index: number) {
    // Check if the selected route is already used elsewhere
    const isDuplicate = this.routemodeArray.some(
      (item, i) => i !== index && item.routeId === routeId
    );

    if (isDuplicate) {
      // Reset the current selection to prevent duplicates
      this.routemodeArray[index].routeId = null;
      // Optional: Notify the user with a snackbar
      this.snackBar.open('This route is already selected!', 'Close', { duration: 3000 });
    }

    // Keep your existing routeCheck logic here if needed
  }

  // Helper method to show validation errors in the template
  hasDuplicateRoute(index: number): boolean {
    const currentId = this.routemodeArray[index].routeId;
    if (!currentId) return false;
    return this.routemodeArray.some((item, i) => i !== index && item.routeId === currentId);
  }
}

2. Update Your Template to Show Validation Errors

Modify your existing template to display an error message when a duplicate selection is detected:

<div *ngFor="let routeval of routemodeArray; let i=index" layout-gt-xs="row">
  <div>
    <mat-form-field>
      <mat-select 
        placeholder="Select Route" 
        [(ngModel)]="routeval.routeId" 
        name="routeName{{i}}" 
        (selectionChange)="routeCheck(routeval.routeId, i)"
        required
      >
        <mat-option [value]="null">Select Route</mat-option>
        <mat-option [value]="route.id" *ngFor="let route of getallRoutes">
          {{ route.name }} <!-- Replace with your route display property -->
        </mat-option>
      </mat-select>

      <!-- Required field error -->
      <mat-error *ngIf="!routeval.routeId">
        Route selection is required
      </mat-error>

      <!-- Duplicate selection error -->
      <mat-error *ngIf="hasDuplicateRoute(i)">
        This route is already selected in another dropdown!
      </mat-error>
    </mat-form-field>
  </div>
</div>

Key Notes:

  • The hasDuplicateRoute method checks if the current dropdown's selection exists in any other dropdown in the array.
  • The routeCheck method not only runs your existing logic but also resets the selection if a duplicate is detected, preventing invalid state entirely.
  • The mat-error elements will automatically show up when their conditions are met, thanks to Angular Material's form field integration.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:50:00