首页 > 解决方案 > 如何从复选框列表中返回所有选中和未选中的值?

问题描述

stackblitz 示例 我正在使用以下数据对象创建复选框列表:

data = [
 { Key: "class_id", displayName: "Section ID", enabled: true },
 { Key: "room_l4", displayName: "Location", enabled: false },
 { Key: "section", displayName: "Section", enabled: true },
 { Key: "section_2", displayName: "Section 2", enabled: true },
 { Key: "campus", displayName: "Description", enabled: true }
 ] 

当用户选择复选框时,我想将“启用”从 false 更改为 true,反之亦然。单击提交按钮后,我想以现在的方式控制台记录数据对象,除了“启用”字段的更改值。例如,如果用户取消选中 data[0].enabled 的复选框,那么我的预期结果将是:

 data = [
 { Key: "class_id", displayName: "Section ID", enabled:false },
 { Key: "room_l4", displayName: "Location", enabled: false },
 { Key: "section", displayName: "Section", enabled: true },
 { Key: "section_2", displayName: "Section 2", enabled: true },
 { Key: "campus", displayName: "Description", enabled: true }
 ] 

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})

export class AppComponent implements OnInit {
myForm: FormGroup
name = 'Angular';
data = [
  { Key: "class_id", displayName: "Section ID", enabled: true },
  { Key: "room_l4", displayName: "Location", enabled: false },
  { Key: "section", displayName: "Section", enabled: true },
  { Key: "section_2", displayName: "Section 2", enabled: true },
  { Key: "campus", displayName: "Description", enabled: true }
  ]
  onSubmit(e){
  console.log(e)
  }
  ngOnInit() {
  this.myForm = new FormGroup({
  name: new FormControl('valu'),
  });
  }

  }

app.component.html

    <form  [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
     <ul class="list-group list-group-flush" *ngFor="let a of data">
        <li class="list-group-item">
          <input
            formControlName="name" 
            (click)="onSubmit()"
            type="checkbox"
            [checked]="a.enabled"
          />
          {{ a.displayName }}
        </li>
      </ul>
      <button>Submit</button>
      </form>

标签: javascripthtmlangulartypescript

解决方案


有一个选项可以简单地使用[(ngModel)]和避免使用表单。一起工作this.data

https://stackblitz.com/edit/angular-ach8xw?file=src%2Fapp%2Fapp.component.html


推荐阅读