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

如何点击按钮获取ngFor渲染表格中的复选框值与对应ID数组

解决Angular中获取复选框值与对应文档ID的问题

要实现点击按钮获取所有复选框状态及对应文档ID的需求,你需要修改复选框的绑定方式,并在提交方法中提取目标数据,具体步骤如下:

修改app.component.html

将复选框改为双向绑定,确保用户勾选/取消操作能同步更新原数组数据:

<div class="container-fluid mt-3">
  <h2>Document Types List</h2>
  <table class="table">
    <thead>
      <tr>
        <th>Allow Expired</th>
        <th>Document Types Id</th>
        <th>Document Types Name</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let documenttype of documenttypes; let i = index">
        <td> 
          <input class="form-check-input" type="checkbox" [(ngModel)]="documenttype.allowexpired"> 
          {{documenttype.allowexpired}}
        </td>
        <td>{{documenttype.docid}}</td>
        <td>{{documenttype.docname}}</td>
      </tr>
    </tbody>
  </table>
  <button type="submit" (click)="submitExpired()" class="btn btn-primary">Save</button>
</div>

修改app.component.ts

在提交方法中提取所需字段,生成目标格式的数组:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  documenttypes: any[] = [
    {
      allowexpired: true,
      docid: 1,
      docname: 'document1',
    },
    {
      allowexpired: true,
      docid: 2,
      docname: 'document2',
    },
    {
      allowexpired: false,
      docid: 3,
      docname: 'document3',
    },
    {
      allowexpired: false,
      docid: 4,
      docname: 'document4',
    },
  ];

  ngOnInit() {}

  submitExpired() {
    // 提取allowexpired和docid字段,生成目标数组
    const resultArray = this.documenttypes.map(item => ({
      allowexpired: item.allowexpired,
      docid: item.docid
    }));
    
    console.log(resultArray);
    // 此处可将resultArray用于接口提交等后续操作
  }
}

必要配置

双向绑定依赖FormsModule,需在AppModule中导入:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

核心逻辑说明

  • 双向绑定[(ngModel)]:让复选框状态与documenttypes数组中的allowexpired属性实时同步,用户操作后数组数据自动更新。
  • map方法转换数组:遍历原数组,只保留需要的allowexpired和docid字段,生成符合要求的数组格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 23:02:40