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

Angular:如何从NgForm中正确获取嵌套对象?

解决Angular NgForm中嵌套对象的键值对获取问题

问题根源

你当前的代码把嵌套的school对象直接通过字符串插值绑定到ngModel,Angular会自动调用toString()把对象转成"[object Object]";同时没有遍历嵌套对象的内部属性,表单无法识别嵌套结构,导致myForm.value里的school是字符串而非对象。

解决方案

需要区分普通属性和嵌套对象,对嵌套对象递归遍历其属性,同时使用点符号命名表单控件(如school.id),并且用双向绑定[(ngModel)]而非字符串插值。

1. 模板代码修改

<form #myForm="ngForm">
  <!-- 遍历User的顶层属性 -->
  <div *ngFor="let item of user | keyvalue">
    <!-- 判断当前值是否为对象(排除null/undefined) -->
    <ng-container *ngIf="typeof item.value === 'object' && item.value !== null">
      <!-- 遍历嵌套的School对象属性,用点符号命名name -->
      <div *ngFor="let nestedItem of item.value | keyvalue">
        <label>{{item.key}}.{{nestedItem.key}}</label>
        <input [(ngModel)]="user[item.key][nestedItem.key]" 
               name="{{item.key}}.{{nestedItem.key}}" 
               type="text">
      </div>
    </ng-container>
    <!-- 处理普通非对象属性 -->
    <ng-container *ngIf="typeof item.value !== 'object' || item.value === null">
      <label>{{item.key}}</label>
      <input [(ngModel)]="item.value" 
             name="{{item.key}}" 
             type="text">
    </ng-container>
  </div>
</form>

<!-- 测试按钮 -->
<button (click)="logFormValue()">查看表单值</button>

2. 组件代码补充

确保组件里初始化了完整的user对象(包含嵌套的school):

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

export interface School {
  id: number;
  name: string;
  address: string;
}

export interface User {
  id: number;
  name: string;
  surname: string;
  school: School;
}

@Component({
  selector: 'app-user-form',
  templateUrl: './user-form.component.html',
})
export class UserFormComponent {
  @ViewChild('myForm') myForm!: NgForm;

  // 初始化完整的User对象,包含嵌套的School
  user: User = {
    id: 1,
    name: '',
    surname: '',
    school: {
      id: 0,
      name: '',
      address: ''
    }
  };

  logFormValue() {
    console.log(this.myForm.value);
    // 输出会是你需要的嵌套结构
  }
}

关键说明

  • 双向绑定[(ngModel)]:直接绑定到对象属性,避免字符串插值导致的对象转字符串问题。
  • 点符号命名控件name:school.id这种命名方式会让NgForm自动将值组装成嵌套对象结构。
  • 类型判断:通过typeof item.value === 'object' && item.value !== null区分普通属性和嵌套对象,避免遍历null/undefined或基本类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:23:09