I am trying to add data to table2 from table1, So i have used data1 and data2 array object.
If i click the checkbox from table 1 i want to add that object to data2.
If i click the checkbox from table 2 i want to remove that object from data2.
I do not know how to get that selected row index by clicking the checkbox. If anyone knows please help to find the solution.
Demo: https://stackblitz.com/edit/angular-ivy-8dfjxs?file=src%2Fapp%2Fapp.component.html
app.component.html:
<h5 class="text-center">Table 1</h5>
<div class="table1">
<table class="table table-bordered">
<thead></thead>
<tbody>
<ng-container *ngFor="let row of data">
<tr>
<td><input type="checkbox" /></td>
<td (click)="row.isExpand = !row.isExpand">
<i *ngIf="!row.isExpand" class="bi-chevron-right"></i>
<i *ngIf="row.isExpand" class="bi-chevron-up"></i>
{{ row.name }}
</td>
</tr>
<tr *ngIf="row.isExpand">
<td colspan="2">
{{ row.expandData }}
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
<button (click)="addSelectedRow()">Add Selected Row To The Table2</button>
<h5 class="text-center">Table 2</h5>
<div class="table2">
<table class="table">
<thead></thead>
<tbody>
<ng-container *ngFor="let row of data2">
<tr>
<td><input type="checkbox" name="box" /></td>
<td (click)="row.isExpand = !row.isExpand">
<i *ngIf="!row.isExpand" class="bi-chevron-right"></i>
<i *ngIf="row.isExpand" class="bi-chevron-up"></i>
{{ row.name }}
</td>
</tr>
<tr *ngIf="row.isExpand">
<td colspan="2">
{{ row.expandData }}
</td>
</tr>
</ng-container>
</tbody>
</table>
</div>
<button (click)="removeSelectedRow()">
Remove Selected Row From The Table2
</button>
app.component.ts:
addSelectedRow(){
let selectedRowIndexFromTable1 = ??//How to get selected row index?
this.data2.push(this.data1[selectedRowIndexFromTable1]);
}
removeSelectedRow(){
let selectedRowIndexFromTable2 = ??//How to get selected row index?
this.data2.splice(this.data2[selectedRowIndexFromTable2]);
}
To achieve this, you can make the following modifications to your code:
isSelected
to each object indata
anddata2
arrays to keep track of whether the checkbox is selected or not.[(ngModel)]
directive to bind theisSelected
property to the checkbox in the template.addSelectedRow
andremoveSelectedRow
functions, useArray.findIndex
to find the index of the selected row based on theisSelected
property.Here's the updated code:
app.component.ts:
app.component.html:
Don't forget to import
FormsModule
in your module to enable the use of[(ngModel)]
.