In Angular 13, it is common to have a table with checkboxes to allow users to select multiple rows. However, sometimes you may need to retrieve the selected row index based on the checkbox selection. In this article, we will explore how to achieve this functionality in Angular 13.
First, let's start by creating a basic table with checkboxes. We will use Angular Material for this example, but you can use any UI library or custom styles as per your project requirements.
<table>
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of people; let i = index">
<td>
<mat-checkbox (change)="onCheckboxChange($event, i)"></mat-checkbox>
</td>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</tbody>
</table>
In the above code, we have a table with three columns: "Select", "Name", and "Age". The *ngFor directive is used to iterate over the "people" array and display each person's details in a row. We also bind the index value to the "i" variable using the "let i = index" syntax.
Inside the table, we have a checkbox for each row. We bind the "change" event to the "onCheckboxChange" method and pass the event object and the index "i" as arguments.
Now, let's implement the "onCheckboxChange" method in our component to handle the checkbox selection and retrieve the selected row index.
onCheckboxChange(event: any, index: number) {
if (event.checked) {
console.log("Selected index:", index);
}
}
In the above code, we check if the checkbox is checked using the "event.checked" property. If it is checked, we log the selected row index to the console. You can replace the console.log statement with your desired logic, such as storing the selected index in a variable or performing any other action.
By implementing the above code, you can now retrieve the selected row index based on the checkbox selection in Angular 13. Feel free to customize the table and checkbox styles as per your project requirements.
References:
| Resource | Description |
|---|---|
| Angular Official Documentation | The official documentation for Angular. |
| Angular Material | Official UI component library for Angular. |