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

Angular动态添加下拉框时,下拉框值互相影响问题求助

问题分析

你遇到的问题核心在于:所有重复生成的下拉框都绑定了同一个全局的country和city变量,导致修改任意一个下拉框的值都会同步到所有实例上。要实现每个过滤器组独立维护自己的选中值,需要让每个过滤器项单独存储自身的国家和城市数据。

解决方案

修改组件类(app.component.ts)

移除全局的country、city变量,让filtersList中的每个对象都持有自己的country和city属性;同时将获取城市列表的逻辑改成接收国家参数的方法,而非依赖全局变量的getter:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  private map = new Map<string, string[]>([
    ['Poland', ['Warszawa', 'Krakow']],
    ['USA', ['New York', 'Austin']],
  ]);
  // 每个过滤器项自带独立的country和city属性
  filtersList: Array<{ country: string; city: string }> = [{ country: '', city: '' }];

  get countries(): string[] {
    return Array.from(this.map.keys());
  }

  // 根据传入的国家参数返回对应城市列表
  getCities(country: string): string[] | undefined {
    return this.map.get(country);
  }

  addFilter() {
    this.filtersList.push({ country: '', city: '' });
  }

  removeFilter(index: number) {
    this.filtersList.splice(index, 1);
  }

  trackByIndex(index: number, item: any) {
    return index;
  }
}

修改模板(app.component.html)

将下拉框的ngModel绑定到当前循环项的country和city属性,调用getCities方法时传入当前项的国家值,同时修复removeFilter的参数传递问题:

<div *ngFor="let filter of filtersList; let i = index; trackBy: trackByIndex">
  <select [(ngModel)]="filter.country">
    <option *ngFor="let country of countries" [value]="country">
      {{ country }}
    </option>
  </select>

  <select *ngIf="filter.country" [(ngModel)]="filter.city">
    <option *ngFor="let city of getCities(filter.country)">{{ city }}</option>
  </select>
  <button (click)="removeFilter(i)">Remove</button>
</div>
<button (click)="addFilter()">Add more filters</button>
说明

修改后,每个过滤器组的下拉框都会绑定到自身所在项的country和city属性,彼此的数据完全独立,修改其中一个组的选中值不会影响其他组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:15:22