如何使用Angular实现基于多级JSON结构的联动下拉列表?
Angular实现三级联动下拉列表(主分类→子分类→孙分类)
我来帮你一步步搞定这个三级联动的下拉需求,咱们从数据准备到组件逻辑再到模板编写,一步步来:
1. 先定义符合要求的JSON数据结构
首先得有匹配需求的数据源,假设你的数据长这样(可以根据实际业务调整字段和内容):
categories = [ { name: 'Mens', subCat: [ { name: 'Shirts', subSubCat: ['Formal', 'Casual', 'Polo'] }, { name: 'Pants', subSubCat: ['Jeans', 'Chinos', 'Formal Trousers'] } ] }, { name: 'Women', subCat: [ { name: 'Dresses', subSubCat: ['Maxi', 'Midi', 'Bodycon'] }, { name: 'Tops' // 这个子分类没有孙分类,后面会处理这种空值情况 } ] }, { name: 'Kids', subCat: [ { name: 'Boys', subSubCat: ['Shirts', 'Shorts', 'Shoes'] }, { name: 'Girls', subSubCat: ['Dresses', 'Skirts', 'Tops'] } ] } ];
2. 组件类(.component.ts)编写联动逻辑
在组件里定义变量存储选中值和下拉选项列表,再写触发联动的方法:
import { Component } from '@angular/core'; @Component({ selector: 'app-category-dropdown', templateUrl: './category-dropdown.component.html', styleUrls: ['./category-dropdown.component.css'] }) export class CategoryDropdownComponent { // 分类数据源 categories = [/* 上面的数组内容 */]; // 存储选中的各级分类 selectedMainCat: string = ''; selectedSubCat: string = ''; selectedSubSubCat: string = ''; // 动态加载的子分类、孙分类列表 subCategories: any[] = []; subSubCategories: string[] = []; // 主分类切换时,更新子分类列表 onMainCatChange() { // 先清空后续下拉的选中值和列表,避免残留旧数据 this.selectedSubCat = ''; this.subSubCategories = []; this.selectedSubSubCat = ''; // 匹配选中的主分类,获取对应的子分类 const targetCategory = this.categories.find(cat => cat.name === this.selectedMainCat); this.subCategories = targetCategory ? targetCategory.subCat : []; } // 子分类切换时,更新孙分类列表 onSubCatChange() { // 清空孙分类选中值 this.selectedSubSubCat = ''; // 匹配选中的子分类,获取对应的孙分类(判断是否存在孙分类字段) const targetSubCat = this.subCategories.find(sub => sub.name === this.selectedSubCat); this.subSubCategories = targetSubCat?.subSubCat || []; } }
3. 模板文件(.component.html)渲染下拉框
用ngModel绑定选中值,(change)事件触发联动方法,同时添加禁用逻辑优化用户体验:
<div class="dropdown-group"> <!-- 主分类下拉框 --> <select [(ngModel)]="selectedMainCat" (change)="onMainCatChange()"> <option value="">请选择主分类</option> <option *ngFor="let cat of categories" [value]="cat.name">{{ cat.name }}</option> </select> <!-- 子分类下拉框:未选主分类时禁用 --> <select [(ngModel)]="selectedSubCat" (change)="onSubCatChange()" [disabled]="!selectedMainCat"> <option value="">请选择子分类</option> <option *ngFor="let sub of subCategories" [value]="sub.name">{{ sub.name }}</option> </select> <!-- 孙分类下拉框:未选子分类或无孙分类时禁用 --> <select [(ngModel)]="selectedSubSubCat" [disabled]="!selectedSubCat || subSubCategories.length === 0"> <option value="">请选择孙分类</option> <option *ngFor="let subSub of subSubCategories" [value]="subSub">{{ subSub }}</option> </select> </div>
4. 必做的配置和优化点
- 别忘了在你的模块(比如
AppModule)里导入FormsModule,因为咱们用了ngModel双向绑定:import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // ...其他导入项 FormsModule ] }) export class AppModule { } - 如果数据是从后端接口获取的,只需要把
categories的初始化改成调用API的逻辑即可; - 可以给下拉框添加自定义样式,让布局更协调;
- 对于没有孙分类的子分类,第三个下拉框会自动禁用,避免用户无效操作。
这样一套下来,就能完美实现你想要的三级联动下拉效果啦!
内容的提问来源于stack exchange,提问作者mayank bisht
相关产品推荐
相关产品推荐

