javascript - 如何从复选框列表中返回所有选中和未选中的值?
问题描述
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>
解决方案
有一个选项可以简单地使用[(ngModel)]
和避免使用表单。一起工作this.data
https://stackblitz.com/edit/angular-ach8xw?file=src%2Fapp%2Fapp.component.html
推荐阅读
- c++ - 立方体 OPENGL 上的缺失面
- vb.net - Datatable 正在从我为 Windows 10 构建的 VB.NET 应用程序中的 SQL 查询结果中接收 (01\dd\yyyy) 格式的日期
- promela - Promela: Why is not this atomic block equivalent to an assignment statement?
- python - 如何去除可能出现在字符串列值开头或结尾的货币字符?
- hadoop - Hive Tez 减速器运行速度超慢
- java - 在二维数组中查找相邻像素而不超出边界
- python - 将具有多种拼写的单词映射到关键字列表的最佳方法?
- ios - iOS:如何以编程方式将 UI 从 LTR 更改为 RTL,反之亦然
- c - 分段错误:使用 strtok,系统调用。C 编程
- windows - git pull changes from remote repo 将更改保存在本地文件中