I am making a project with angular 14 and angular material. I have a table. There is an update button next to each staff member. I want the spinner on the button of the employee I click to work, but they all work, so it is not clear which employee’s information is updated. What do I need to do to make the spinner of the staff I just clicked on work. I would be glad if you help.
<div class="table-responsive">
<table class="table table-hover table-bordered" filterControl="true">
<thead class=" text-primary">
<th>NAME</th>
<th>SURNAME</th>
<th>DATE</th>
<th></th>
</thead>
<tbody>
<tr *ngFor="let personel of dataPersonel ">
<td> <b>{{personel.name}}</b> </td>
<td> {{personel.surname}}</td>
<td> {{personel.date | date:'MM/dd/yyyy'}}</td>
<td>
<button mat-raised-button
class="btn btn-info" (click)="updatePerspnel(personel)">
UPDATE
<mat-icon *ngIf="loading">
<mat-spinner color="primary" diameter="20"> </mat-spinner>
</mat-icon>
</button>
</td>
</tr>
</tbody>
</table>
</div>
loading: boolean = false;
ngOnInit(): void {
}
updatePerspnel(personel) {
this.loading = true;
this.personelService.updatePersonel(personel).subscribe(response => {
if (response === Constants.OK) {
this.alertifyService.makeSuccess();
}else{
this.alertifyService.makeError();
}
this.loading = false;
});
}
2
Answers
To make the spinner on the button of the employee you clicked work without affecting the spinners on other buttons, you need to track the loading state for each employee separately. You can achieve this by adding a
loading
property to each employee object in yourdataPersonel
array. Here’s how you can modify your code to achieve this:loading
property for each employee in thedataPersonel
array.loading
property for each employee to conditionally display the spinner:By adding a
loading
property to each employee object and using it to control the spinner display, you ensure that only the spinner for the clicked employee will be shown while the update operation is in progress. This way, it’s clear which employee’s information is being updated.Because you are using a
personnel
object, i recommend you to declare a new property inside of it calledisLoading
, it can be a simple boolean set by default tofalse
(I personnaly recommend creating a property
status
with an enum for it, to provide more readability and consistency)After that in your template
Then in your logic