【发布时间】:2021-10-05 04:03:59
【问题描述】:
我有一个简单的表,其中包含描述和代表状态的两列:YES 和 NO。
每个复选框代表一个对象,其中包含启动时为空的“条件”属性。根据标记的内容,形成一个对象数组。我想做的就是选择同一行中的另一个复选框时,删除先前创建的对象。不影响其他行。
例如当我选择一个复选框时:
通过选中另一个复选框,我想删除以前的对象
我正在检查事件并进行更改以防止用户选择同一行中的两个复选框。还可以通过取消选中选中的复选框来删除创建的对象,使“条件”为真或假。
我有一个关于 stackblitz 的演示:Demo
.HTML
<form [formGroup]="demoFormGroup" style="margin-top:20px; margin-bottom:30px">
<div formArrayName="info">
<table>
<tr>
<th></th>
<th>YES</th>
<th>NO</th>
</tr>
<tr *ngFor="let x of data; let i = index">
<td>{{x.Description}}</td>
<td>
<mat-checkbox
(change)="onChange($event,x,true)"
[checked]="x.Condition"
></mat-checkbox>
</td>
<td>
<mat-checkbox
(change)="onChange($event,x,false)"
[checked]="x.Condition != null && !x.Condition"
></mat-checkbox>
</td>
</tr>
</table>
</div>
</form>
<pre>{{ demoFormGroup.get('info')?.value | json }}</pre>
.TS
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
demoFormGroup: FormGroup;
data: any;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.demoFormGroup = this.fb.group({
info: this.fb.array([])
});
this.data = [
{
Id: 4,
Description: 'Option 1',
Condition: null
},
{
Id: 6,
Description: 'Option 2',
Condition: null
}
];
}
onChange(event: any, option: any, enabled: boolean) {
option.Condition = enabled;
const ctrl = (<FormArray>this.demoFormGroup.get('info')) as FormArray;
if (event.checked) {
ctrl.push(new FormControl(option));
} else {
this.removeObject(ctrl, event);
}
}
removeObject(ctrl: any, event: any) {
const i = ctrl.controls.findIndex(
(x: any) => x.value === event.source.value
);
ctrl.removeAt(i);
}
}
【问题讨论】:
-
你的对象被复制了吧?
-
@FaizalHussain 唯一改变的是属性“条件”根据在真或假中选择的复选框
-
为什么要使用复选框?如果您只想选择一个值,可以使用单选按钮
标签: arrays angular object checkbox