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

Angular mat-select下拉框获取API数据后无法渲染显示如何解决

mat-select下拉不显示修复方案

需修改的3个核心问题

1. 变量名不匹配

TS文件中存储肌肉组接口返回数据的变量名为单数muscleGroup,但HTML模板中*ngFor遍历的是复数muscleGroups,变量名不一致导致无法读取数据。
修改TS文件中的变量声明:

// 原错误写法
// muscleGroup = {} as IMuscleGroups[];
// 修改为
muscleGroups: IMuscleGroups[] = [];

同时接口请求成功后赋值对应修改为:

.subscribe((muscleGroupsData: IMuscleGroups[]) => {
    this.muscleGroups = muscleGroupsData;
    console.log(this.muscleGroups);
})

2. 绑定属性大小写错误

Angular输入绑定大小写敏感,模板中mat-option写的[Value]是大写开头,不符合Angular规范,需改为小写开头的[value]。

3. 对象插值格式错误

IMuscleGroups是对象类型,直接写{{muscleGroup}}会渲染为[object Object],需要取出对象中存储肌肉组名称的对应字段渲染,假设接口返回字段为muscleGroupName,则插值改为{{muscleGroup.muscleGroupName}}即可,字段名可根据你实际的IMuscleGroups接口定义调整。

修改后的mat-select代码示例

<mat-form-field appearance="fill">
    <mat-label>Muscle Group</mat-label>
    <!-- 后续对接表单可补充formControlName,同时在FormGroup中新增对应控件 -->
    <mat-select>
        <mat-option *ngFor="let muscleGroup of muscleGroups" [value]="muscleGroup">
            {{muscleGroup.muscleGroupName}}
        </mat-option>
    </mat-select>
</mat-form-field>

完成以上修改后下拉即可正常显示数据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:54:03