You need to enable JavaScript to run this app. Angular中基于多API数据实现三级级联下拉菜单的解决方案
优惠活动
大模型
产品
解决方案
定价
更多

Angular中基于多API数据实现三级级联下拉菜单的解决方案

Angular 三级级联下拉实现方案

修改说明

  • 新增filteredCities、filteredBlocks两个中间变量,分别存储当前选中国家对应的城市列表、当前选中城市对应的区域列表,原始全量接口返回数据保持不变
  • 新增选中变化处理方法,上级下拉框选中后自动过滤下级选项列表,同时清空下级已选值避免脏数据
  • 修复原有模板中城市下拉框的字段绑定错误:API返回的城市列表中,name字段为所属国家名,city字段才是城市名
  • 请确保你的业务模块已经导入FormsModule,否则ngModel双向绑定会失效

完整 component.ts 代码

import { Component, OnInit } from '@angular/core';
import { InfraRequestService } from '你的服务实际路径';

export class CreateInfraRequestComponent implements OnInit {
  // 原始全量接口返回数据
  Country: any[] = [];
  City: any[] = [];
  Block: any[] = [];
  // 下拉框选中值
  selectedCountry: string = '';
  selectedCity: string = '';
  selectedBlock: string = '';
  // 过滤后的级联展示数据
  filteredCities: any[] = [];
  filteredBlocks: any[] = [];

  constructor(private infraService : InfraRequestService){}

  ngOnInit(): void {
    this.getAllCountry();
    this.getAllCity();
    this.getAllblock();
  }

  getAllCountry (){
    this.infraService.getAllInfraRequest("apiUrlForCountry").subscribe((data)=>{
      this.Country = data;
    });
  }

  getAllCity(){
    this.infraService.getAllInfraRequest("apiUrlForCity").subscribe((data)=>{
      this.City = data;
    });    
  }

  getAllblock(){
    this.infraService.getAllInfraRequest("apiUrlForBlock").subscribe((data)=>{
      this.Block = data;
    });    
  }

  // 国家切换处理逻辑
  onCountryChange() {
    // 过滤当前选中国家对应的所有城市
    this.filteredCities = this.City.filter(item => item.name === this.selectedCountry);
    // 重置下级所有选中状态
    this.selectedCity = '';
    this.filteredBlocks = [];
    this.selectedBlock = '';
  }

  // 城市切换处理逻辑
  onCityChange() {
    // 过滤当前选中城市对应的所有区域,如需兼容大小写可以统一转小写判断:item.dist.toLowerCase() === this.selectedCity.toLowerCase()
    this.filteredBlocks = this.Block.filter(item => item.dist === this.selectedCity);
    // 重置下级选中状态
    this.selectedBlock = '';
  }
}

完整 component.html 代码

<!-- 国家选择下拉框 -->
<select [(ngModel)]="selectedCountry" (ngModelChange)="onCountryChange()">                   
  <option *ngFor="let country of Country" [value]="country.name">
    {{country.name}}
  </option>            
</select>

<!-- 城市选择下拉框 -->
<select [(ngModel)]="selectedCity" (ngModelChange)="onCityChange()">                   
  <option *ngFor="let city of filteredCities" [value]="city.city">
    {{city.city}}
  </option>            
</select>

<!-- 区域选择下拉框 -->
<select [(ngModel)]="selectedBlock">                   
  <option *ngFor="let block of filteredBlocks" [value]="block.name">
    {{block.name}}
  </option>            
</select>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 13:54:03