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

Angular如何实现动态添加带输入框、新增/删除按钮的fieldset功能

实现方案

你可以通过维护一个存储分钟值的数组,配合Angular的*ngFor指令动态渲染输入行,增删操作直接操作这个数组即可,具体实现如下:

1. 组件TS逻辑

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

@Component({
  selector: 'app-minute-form',
  templateUrl: './minute-form.component.html',
  styleUrls: ['./minute-form.component.css']
})
export class MinuteFormComponent {
  // 存储所有行的分钟值,初始化默认保留一行
  minuteList: number[] = [15];

  // 新增输入行
  addMinuteRow(): void {
    // 新增行默认值可自行调整,这里设为15
    this.minuteList.push(15);
  }

  // 删除指定索引的输入行
  deleteMinuteRow(index: number): void {
    if (this.minuteList.length > 1) {
      this.minuteList.splice(index, 1);
    }
  }
}

2. 组件HTML模板

<!-- 遍历数组生成每一行,带索引方便操作对应项 -->
<div *ngFor="let minute of minuteList; let i = index" class="minute-row">
  <label [for]="'MinuteInput_' + i">In Minute </label>
  <input 
    type="number" 
    [id]="'MinuteInput_' + i" 
    [(ngModel)]="minuteList[i]"
    min="0" 
    max="45" 
    step="15"
  >
  <button type="button" (click)="addMinuteRow()">+</button>
  <!-- 仅当行数量大于1时显示删除按钮 -->
  <button 
    type="button" 
    *ngIf="minuteList.length > 1" 
    (click)="deleteMinuteRow(i)"
  >-</button>
</div>

补充说明

  • 输入框通过step="15" min="0" max="45"的原生属性,已经限制了只能输入0、15、30、45四个值,完全符合需求
  • 如果使用ngModel双向绑定,需要在所属模块中导入FormsModule
  • 如果项目用响应式表单,可以把minuteList替换为FormArray管理,更方便做全局表单校验和统一值收集

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:54:00