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>
慕码人2483693
紫衣仙女
相关分类