如何在Angular Formly中将后端返回的城市数据填充到select下拉框中
Angular Formly 动态填充select下拉选项实现方案
实现步骤
- 组件中注入你封装的城市接口服务
- 把Formly字段配置定义为组件变量,select字段的
templateOptions.options初始化为空数组 - 组件初始化时调用城市接口,将返回数据处理为
{value: 选项值, label: 选项展示文本}的格式后,赋值给对应字段的options属性
完整代码示例
组件.ts文件代码:
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { FormlyFieldConfig } from '@ngx-formly/core'; import { Subscription } from 'rxjs'; // 替换为你自己的服务路径 import { CityService } from './city.service'; @Component({ selector: 'app-city-select', templateUrl: './city-select.component.html', }) export class CitySelectComponent implements OnInit, OnDestroy { form = new FormGroup({}); fields: FormlyFieldConfig[] = []; private citySub: Subscription | null = null; constructor(private cityService: CityService) {} ngOnInit(): void { // 初始化Formly字段配置 this.fields = [ { key: 'city', type: 'select', className: 'select-stlyes', templateOptions: { label: '城市', options: [], // 初始为空 required: true, }, }, // 其余字段配置... ]; // 调用接口获取城市列表 this.citySub = this.cityService.getcitiNames().subscribe({ next: (res) => { // 按接口实际返回结构调整映射规则 // 示例假设接口返回格式为 [{id: 110100, name: '北京市'}, ...] const cityOptions = res.map(item => ({ value: item.id, label: item.name })); // 通过key匹配找到对应字段,赋值options,避免索引匹配出错 const cityField = this.fields.find(field => field.key === 'city'); if (cityField?.templateOptions) { cityField.templateOptions.options = cityOptions; } }, error: (err) => { console.error('城市列表获取失败', err); } }) } ngOnDestroy(): void { // 取消订阅避免内存泄漏 this.citySub?.unsubscribe(); } }
注意事项
- 如果接口返回的数组本身已经是
{value, label}结构,不需要额外映射,直接赋值即可 - 优先用
key匹配字段,不要用固定索引,后续字段顺序调整时不会出错
内容的提问来源于stack exchange,提问作者user
相关产品推荐
相关产品推荐

