Home > Net >  trackBy in ngfor not worker Angular
trackBy in ngfor not worker Angular

Time:03-19

I am working with mat-slide-toggle to update the state of a field in my database (Firestore). The problem is that I see that it has a strange behavior in the other elements when pressing it (a flicker).

I've been reading that using trackBy prevents these types of behavior. I used it but the error stays.

enter image description here

lista-items.component.html

<app-card-item-admin *ngFor="let item of group.items; let i = index; trackBy: trackByPublicado" [idNegocio]="idNegocio" [item]="item"></app-card-item-admin>

lista-items.components.ts

actualizarPublicado(idItem, publicado) { this.afs.collection('negocios').doc(this.idNegocio).collection('items').doc(idItem).update({publicado});
  }    

trackByPublicado(item) {
      return item.publicado;
    }

card-item-admin.component.html

<div >

  <div >

    <div >
      <img  [src]="item.image">
    </div>

    <div >
      <p >{{item.nombre}}</p>
      <p >{{item.descripcion | slice:0:32}}...</p>
      <span  [ngClass]=" !item.precioDescuento ? 'text-decoration-line-through small text-muted' : 'precioItem' " *ngIf="item.precioDescuento">S/. {{item.precioDescuento}}</span>
      <span [ngClass]=" item.precioDescuento ? 'text-decoration-line-through small text-muted' : 'precioItem' " >S/. {{item.precio}}</span>
    </div>

    <div >
      <mat-slide-toggle color="primary" #toggle [ngModel]="item.publicado" (ngModelChange)="actualizarPublicado(item.id, $event)">
      </mat-slide-toggle>
    </div>

  </div>
</div>

CodePudding user response:

I think, the reason is the way you use ngModel and ngModelChange, try to switch to just using checked property and change event for mat-slide-toggle like below

actualizarPublicado(idItem, change: MatSlideToggleChange) { 
 this.afs.collection('negocios')
   .doc(this.idNegocio)
   .collection('items')
   .doc(idItem)
   .update({
      publicado: change.checked
   });
}  


<mat-slide-toggle
  #toggle
  color="primary"
  [checked]="item.publicado"
  (change)="actualizarPublicado(item.id, $event)">
</mat-slide-toggle>
  • Related