Using trackBy in ngFor does not function properly in Angular

I have been using mat-slide-toggle to update the state of a field in my Firestore database. However, I have noticed a strange flickering behavior in other elements when I press it.

I have read that using trackBy can prevent these types of issues. I tried implementing it, but the problem persists.

https://i.sstatic.net/Nc3fC.gif

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>

Answer №1

One possible solution could be to simplify the use of ngModel and ngModelChange by switching to only using the checked property and change event for mat-slide-toggle. See the example below for implementation:

updatePublished(idItem, change: MatSlideToggleChange) { 
 this.afs.collection('businesses')
   .doc(this.businessId)
   .collection('items')
   .doc(idItem)
   .update({
      published: change.checked
   });
}  


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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choosing a specific row in Angular 5

I'm completely new to Angular, so please bear with me :) I have a collection of user data that is presented in the following format: https://i.sstatic.net/5UAIP.png Below is my current HTML structure: EDIT - ADDED CRUD BUTTONS : <!--Add ...

Issue encountered while deploying Firebase Functions: Unable to parse function triggers

Experiencing difficulty deploying firebase functions from an angular project after updating to the latest firebase-tools 7.8.1 version. The project's package.json contains "firebase-admin": "~6.0.0", "firebase-functions": "^2.1.0", and "firebase-funct ...

Utilizing Electron API within an Angular Component

I'm hoping to utilize a locally stored video file in electron and play it within my angular component. Despite exposing the loadLocalFile function to prevent the need for setting nodeIntegration to true, I keep receiving a Security Warning : This re ...

Tips for implementing react-select types in custom component development

Currently, I'm in the process of developing custom components for DropdownIndicator to be used on react-select with Typescript. However, I am encountering difficulties with the component's type due to my limited experience with Typescript. I wou ...

Issues arise during the deployment of Angular7 production build when passing through the Bitbucket package manager

I am working on a project to create a system that allows Angular components to be reused across multiple applications via BitBucket. Currently, I have the following setup: BitBucket Repo A - This repository stores the node module. The module is develope ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

The ngx-image-cropper's roundCropper attribute is not functioning correctly as it should. An error is being displayed stating: "Type 'string' is not assignable to type 'boolean'"

<image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" format="jpg" (imageCropped)="imageCropped($event)" roundCropper = "true"> </i ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

Obtain the result and retrieve it using `window.angularComponentRef.zone.run`

In my work, I have been able to successfully call angular functions within a component through a static file. For reference, you can visit this link: How to expose angular 2 methods publicly?. The method suggested in the link involves using Zones in Angul ...

Is it possible to load a script conditionally in Angular 2 using the Angular CLI

Is it possible to conditionally load scripts using Angular CLI? I am looking to dynamically load a script in this file based on the environment or a variable. For example, I want to load a specific script in production but not in development. How can I ac ...

Issue: You cannot render objects as a React child element (object found with properties {name}). If you intended to display multiple children, consider using an array instead

I have just finished creating a new Provider and now I want to test it. To do this, I am setting up a mock Component within the test file. // TasksProvider.spec.tsx const task = { name: 'New Task', } function TestComponent() { const { tasks ...

What is causing elements like divs, paragraphs, or text not to display within an ion-item after an ion-input is added?

I am currently working on validating a simple form and everything seems to be functioning properly. However, I have encountered an issue with displaying text messages within an ionic 3 list item. The ion-item consists of an ion-input element. When I place ...

I am looking to implement a feature in my quiz application where a green tick mark appears next to the question number for the correct answer and a red cross mark for the wrong answer

My HTML code here retrieves questions from a database and displays them based on the question number. <h4>{{indexOfelement+1}}</h4>&nbsp;&nbsp; In my CSS, I need to style the questions as follows: How can I achieve this? Each question ...

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

Designate as a customizable class property

I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. T ...

Tips for accessing the Components.inputs array in Angular

I've noticed that in Angular, you have the ability to define inputs within the @Component decorator. @Component({ selector: 'my-component', changeDetection: ChangeDetectionStrategy.OnPush, template: '<ng-content></ng-c ...

Exploring the capabilities of the Angular 2 HTTP service

I am just beginning my journey with Angular 2. Here is a service I have created: @Injectable() export class PostsService { constructor(private http: Http) { } getAllPosts() { return this.http.get('/api/posts') .map ...

Encountering an issue when attempting to attach an event listener to the entire document

I need help troubleshooting an issue with a function that is supposed to perform certain operations when the scrollbar is moved. I attached an event listener to the document using an ID, but it's resulting in an error. ERROR Message: TypeError: Canno ...

Issue with Prettier AutoFormatting in a project that combines TypeScript and JavaScript codebases

Recently, I've started incorporating TypeScript into an existing JavaScript project. The project is quite large, so I've decided to transition it to TypeScript gradually. Below is a snippet from my eslintrc.js file: module.exports = { parser: ...