Angular 6动态复选框返回ID数组。
创始人
2024-10-16 08:00:50
0

在Angular 6中,可以通过使用ngModel和FormControl来实现动态复选框返回ID数组的功能。下面是一个示例代码:

在组件的HTML文件中,使用ngFor循环来动态生成复选框,并将复选框的值绑定到FormControl中:

在组件的TS文件中,定义复选框的选项和FormControl,并在change事件中更新选中的复选框:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

@Component({
  selector: 'app-checkbox-example',
  templateUrl: './checkbox-example.component.html',
  styleUrls: ['./checkbox-example.component.css']
})
export class CheckboxExampleComponent {
  checkboxForm: FormGroup;
  checkboxes: any[] = [
    { id: 1, name: 'Checkbox 1' },
    { id: 2, name: 'Checkbox 2' },
    { id: 3, name: 'Checkbox 3' }
  ];
  selectedCheckboxes: number[] = [];

  constructor(private formBuilder: FormBuilder) {
    this.checkboxForm = this.formBuilder.group({});
    this.checkboxes.forEach((checkbox) => {
      this.checkboxForm.addControl(checkbox.id.toString(), new FormControl(false));
    });
  }

  updateSelectedCheckboxes(checkbox: any) {
    if (this.checkboxForm.get(checkbox.id.toString()).value) {
      this.selectedCheckboxes.push(checkbox.id);
    } else {
      const index = this.selectedCheckboxes.indexOf(checkbox.id);
      if (index > -1) {
        this.selectedCheckboxes.splice(index, 1);
      }
    }
  }
}

在这个示例中,复选框选项存储在checkboxes数组中,每个复选框的值绑定到FormControl中。通过在change事件中更新selectedCheckboxes数组,可以跟踪选中的复选框。

相关内容

热门资讯

透视推荐!pokemmo脚本手... 透视推荐!pokemmo脚本手机版(透视)wepoker有用吗,教程烘培(今日头条)-哔哩哔哩1、起...
pokermaster破解版!... pokermaster破解版!wepoker提高好牌率(透视)app-确实揭幕是真的挂1、下载好we...
透视开挂!菠萝辅助器免费版的特... 透视开挂!菠萝辅助器免费版的特点(透视)智星德州辅助译码插件靠谱吗,教程模块(有挂技术)-哔哩哔哩1...
wpk软件是真的吗!红龙pok... wpk软件是真的吗!红龙poker辅助器免费观看(透视)教程-果然详情是真的挂1、红龙poker辅助...
hhpoker软件靠谱吗!hh... hhpoker软件靠谱吗!hhpoker辅助靠谱吗(透视)工具-原来开挂存在有挂1、首先打开hhpo...
透视详细!wepoker代打辅... 您好,wpk透视怎么安装这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
wepoker辅助器如何使用!... wepoker辅助器如何使用!德州hhpoker是真的吗(透视)软件-切实分享是真的挂小薇(辅助器软...
透视曝光!wepoker透视挂... 透视曝光!wepoker透视挂底牌(透视)fishpoker透视,教程绝活(有挂技术)-哔哩哔哩1、...
wepoker公共底牌!wep... wepoker公共底牌!wepoker怎么看底牌(透视)挂-都是详情真的是有挂小薇(辅助器软件下载)...
wepoker开辅助能查到吗!... wepoker开辅助能查到吗!pokemmo辅助器(透视)器-其实解密真的有挂1)wepoker开辅...