简体   繁体   中英

trackBy in ngfor not worker Angular

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.

在此处输入图像描述

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 class="position-relative bg-white rounded-3 border">

  <div class="d-flex justify-content-between">

    <div class="me-2">
      <img class="imageItemAdmin rounded-start" [src]="item.image">
    </div>

    <div class="w-100">
      <p class="nombreItem mb-0 mt-1 lh-1">{{item.nombre}}</p>
      <p class="descripcionItem mb-0">{{item.descripcion | slice:0:32}}...</p>
      <span class="me-2" [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 class="pe-2 pt-2">
      <mat-slide-toggle color="primary" #toggle [ngModel]="item.publicado" (ngModelChange)="actualizarPublicado(item.id, $event)">
      </mat-slide-toggle>
    </div>

  </div>
</div>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM