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

Angular表单如何生成包含对象数组的JSON返回值?

解决Angular模板驱动表单提交含对象数组的JSON问题

问题根源

你当前的表单代码存在几个核心问题:

  • 所有输入框重复绑定到全局的name、wins、loses变量,无法区分不同队伍的字段值
  • 未给模板驱动表单的输入框指定name属性,Angular无法正确收集表单控件值
  • teams数组的绑定逻辑错误,*ngFor循环没有关联到数组的具体元素,导致无法生成预期的数组结构

修正后的表单代码

<form id="form" #ContestForm="ngForm" (ngSubmit)="addNewContest(ContestForm.value)">
  <!-- 赛事名称 -->
  <div class="form-group">
    <input 
      type="text" 
      name="contestName" 
      [(ngModel)]="contest.name" 
      class="form-control" 
      placeholder="Contest Name">
  </div>

  <br>

  <!-- 队伍列表,循环渲染数组元素 -->
  <div *ngFor="let team of contest.teams; let index = index" class="form-group">
    <br>
    <label>Team {{index + 1}} :</label>
    <br><br>
    
    <input 
      type="text" 
      name="teamName_{{index}}" 
      [(ngModel)]="team.name" 
      class="form-control" 
      placeholder="Name">
    
    <br>
    <div class="form-group">
      <input 
        type="number" 
        name="teamWins_{{index}}" 
        [(ngModel)]="team.wins" 
        class="form-control" 
        placeholder="Wins">
    </div>
    
    <br>
    <div class="form-group">
      <input 
        type="number" 
        name="teamLoses_{{index}}" 
        [(ngModel)]="team.loses" 
        class="form-control" 
        placeholder="Loses">
    </div>
  </div>

  <br>
  <button type="submit">提交</button>
</form>

组件类(TypeScript)代码

在组件的.ts文件中初始化表单绑定的对象,确保teams是包含初始元素的数组:

import { Component } from '@angular/core';

@Component({
  selector: 'app-contest-form',
  templateUrl: './contest-form.component.html',
  styleUrls: ['./contest-form.component.css']
})
export class ContestFormComponent {
  // 初始化表单绑定的对象,包含赛事名称和队伍数组
  contest = {
    name: '',
    teams: [
      { name: '', wins: 0, loses: 0 },
      { name: '', wins: 0, loses: 0 }
    ]
  };

  addNewContest(formValue: any) {
    // formValue就是你预期的JSON结构
    console.log('提交的表单值:', formValue);
    // 这里可以继续处理提交逻辑,比如调用API
  }
}

关键说明

  1. 绑定路径正确:每个队伍的字段直接绑定到contest.teams数组的对应元素(team.name、team.wins等),确保每个队伍的输入值独立存储
  2. 必填name属性:每个输入框都添加了唯一的name属性(比如teamName_{{index}}),模板驱动表单依赖这个属性来追踪控件值
  3. 初始数组结构:组件类中预先初始化了teams数组的两个元素,*ngFor循环可以直接遍历渲染,避免空数组导致的渲染问题

提交表单时,ContestForm.value会生成你预期的JSON结构:

{
  "name": "contestName",
  "teams": [
    { "name": "team1", "wins": 1, "loses": 1 },
    { "name": "team2", "wins": 2, "loses": 2 }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:46:08