如何用Angular的*ngFor循环重复生成多组表单输入?
实现高尔夫差点计算应用的模板驱动表单动态分组需求
步骤1:调整组件TS数据结构
把原来的单字段数组拆成「字段定义数组」和「分组数据数组」,初始生成3组空数据,同时限制最大组数为20:
import { Component } from '@angular/core'; @Component({ selector: 'app-score-calculator', templateUrl: './score-calculator.component.html', styleUrls: ['./score-calculator.component.css'] }) export class ScoreCalculatorComponent { // 定义每组包含的5个字段名称 scoreFields: string[] = [ '18 Hole Score', '9 Hole Score', 'Course Rating', 'Slope Rating', 'Score Differential' ]; // 初始生成3组空数据,每组用对象存储对应字段的输入值 scoreGroups: any[] = Array(3).fill({}); // 最大允许组数 maxGroups = 20; // 添加新组的方法 addScoreGroup(): void { if (this.scoreGroups.length < this.maxGroups) { this.scoreGroups.push({}); } } }
步骤2:修改HTML模板,用两层*ngFor生成动态分组
外层遍历分组,内层遍历每组的5个字段,同时给每个输入框绑定ngModel并设置唯一的name属性(模板驱动表单要求name唯一):
<!-- 外层循环:遍历所有分组 --> <div *ngFor="let group of scoreGroups; let groupIdx = index" class="score-group"> <h4>第 {{ groupIdx + 1 }} 组</h4> <!-- 内层循环:遍历当前组的5个输入字段 --> <div *ngFor="let field of scoreFields; let fieldIdx = index" class="field-container"> <label>{{ field }}</label> <input type="number" name="group-{{ groupIdx }}-field-{{ fieldIdx }}" [(ngModel)]="group[field]" step="0.1" placeholder="请输入{{ field }}" > </div> </div> <!-- 添加新组按钮,达到最大组数时禁用 --> <button (click)="addScoreGroup()" [disabled]="scoreGroups.length >= maxGroups" > 添加新组 </button>
步骤3:确保导入FormsModule
模板驱动表单依赖FormsModule,需要在组件所属的模块中导入:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // 导入FormsModule import { AppComponent } from './app.component'; import { ScoreCalculatorComponent } from './score-calculator/score-calculator.component'; @NgModule({ declarations: [ AppComponent, ScoreCalculatorComponent ], imports: [ BrowserModule, FormsModule // 添加到imports数组 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
额外说明
- 每组的输入值会自动存储在
scoreGroups数组的对应对象中,比如scoreGroups[0]['18 Hole Score']就是第一组的18洞成绩。 - 按钮禁用逻辑确保分组数不会超过20组,符合需求。
- 给输入框添加
step="0.1"是因为高尔夫相关评分可能包含小数,根据实际需求可以调整或移除。
内容的提问来源于stack exchange,提问作者Eric Petela
相关产品推荐
相关产品推荐

