I have a simple table with descriptions and two columns representing a state: YES and NO.
Each checkbox represents an object in which it includes the "Condition" property that is null at startup. Depending on what is marked, an array of objects is formed. What I want to do is that when another checkbox in the same row is selected, delete the previously created object. Without affecting the other rows.
For example when I select a checkbox:
And by selecting the other checkbox, I would like to delete the previous object
I was playing around with the event checked and change to prevent the user from selecting the two checkboxes in the same row. Also to delete the created object by unchecking a selected checkbox, making the "Condition" true or false.
I have a demo on 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></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></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);
}
}
Aucun commentaire:
Enregistrer un commentaire