Updating a Firestore document based on the state of a toggle switch on a mat-slider

I am currently working on updating a boolean field in a Firestore document from true to false or vice versa.

Initially, the functionality seems to be working well when I toggle the button on and off. However, at times it stops functioning correctly and requires me to press the button multiple times.

You can view my StackBlitz example here: https://stackblitz.com/edit/angular-ea3wme

myComponent.html

<mat-slide-toggle #toggle [checked]="domiciliario.estado" (change)="actualizarEstado(domiciliario.id)"></mat-slide-toggle>

myComponent.ts

actualizarEstado(key){
this.fs.updateEstado(key);
}

myService.ts

estadoChange: boolean = !false || !true;

updateEstado(key){
this.afs.doc('domiciliarios/' + key).update({
  estado : this.estadoChange = !this.estadoChange
})
}

Answer №1

The issue lies in the synchronization of estadoChange in your service with the edited domiciliario item. To maintain independent status for all items under domiciliarios, you must update each one with its corresponding status using the value from mat-slide-toggle.

You can experiment with ngModel and ngModelChange.

<mat-slide-toggle #toggle [ngModel]="domiciliario.estado" (ngModelChange)="actualizarEstado(domiciliario.id, $event)"></mat-slide-toggle>

// component function
actualizarEstado(key, obj, e){
  this.fs.updateEstado(key, e);
}

// service function
updateEstado(key, estado){
  this.afs.doc('domiciliarios/' + key).update({estado});
}

Check out the fixed demo.


Additional information: Whenever an item is changed, it triggers a value change in Firebase, causing rerendering of all ngFor items. To avoid unnecessary rerendering, consider using trackBy. For more details, refer to the documentation and a solution for improving ngFor performance.

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

What is the method to merge min and max validation errors when using React Hook Form?

<input {...register("subject", { maxLength: 50, minLength: 2, required: true, })} disabled={isLoading} id="subject" autoComplete=&q ...

Guide on TypeScript child classes: defining argument and return types for methods inherited from parent classes

I am facing a scenario where I have a parent class that mandates child classes to implement a unique businesslogic() method. Each child class has its own version of the businesslogic() method with different type signatures. The parent class includes a com ...

Using Angular Material to dynamically hide columns in a table that is being created on the fly

Is there a way to hide columns in my table based on the ID value sent to the page upon opening it? While researching, I found a method for tables with dynamically generated columns in this post: https://github.com/angular/components/issues/9940. However, t ...

Is it possible to dynamically adjust the size of the CircleProgressComponent element in ng-circle-progress?

For my current Angular 11 project, I am facing the challenge of dynamically changing the size of the ng-circle-progress library's CircleProgressComponent element. After some research, I discovered that the element's size can be adjusted by apply ...

An error has occurred in the Angular application while trying to access the 'name' property in the AppComponent_Template

I'm encountering a challenge in my Angular application where I am receiving the following error message: javascript Copy code ERROR TypeError: Cannot read properties of undefined (reading 'name') This issue is present in the app.component. ...

Exploring the functionality of virtualScroll in primeng 6: A comprehensive guide

Currently, I am facing an issue with a dropdown menu that contains over 100 elements. These elements are loaded dynamically through an Angular function under specific conditions. The loading process is time-consuming and takes several seconds to complete. ...

Version 1.9.3 of Redux Toolkit is encountering an error stating that the 'push' property is not found on the type 'WritableDraft<CartState>'

Currently delving into Redux Toolkit using TypeScript and facing a roadblock that seems deceptively simple. Unfortunately, my current knowledge isn't enough to unravel this puzzle and I'm in need of some guidance. The issue arises with an error ...

Resolving undefined in Ionic 4: Returning Data from Modal

I'm attempting to create a modal window that utilizes a radio group. When a user selects a value from the radio group, I want the modal to return the selected object. Here is the code for the radio group page and HTML: export class PopoverstationsPa ...

Error: Unexpected token < occurs when using SVG require in Jest

I'm struggling to locate the source of this error. Currently, I am working with Typescript in React and using Jest and Enzyme for unit testing. Below is a snippet from my Package.json file: "scripts": { "start": "node server.js", "bundle": ...

Discovering the dimensions of a video in Angular 2 using TypeScript

To determine whether the video is portrait or landscape, I am attempting to retrieve the height and width of the video using the following method: import { Component, OnInit, AfterViewInit } from '@angular/core'; @Component({ selector: ' ...

Is it possible to nest a component within another component in the latest iteration of Angular2?

Currently in angular2 version (V2.2.0), I am interested in utilizing a component within another component. In the past, we were able to achieve this by using the following code: import { AnotherComponent } from './another-component'; @Componen ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

What is the best way to handle sending a single request after clearing multiple fields?

I have been using reactive forms and encountered an issue where resetting 5 specific fields triggers multiple requests instead of just one. I intend to send only one request after all changes, but currently, each field reset results in a separate request. ...

What steps should I take to avoid harmful automatic approvals during application launch while utilizing the "angular-auth-oidc-client"?

Utilizing the "angular-auth-oidc-client" in my app is crucial, operating in mode "silent_run": true. The app initiates with various routes, always accompanied by query parameters. Majority of the resources within the application do not necessitate server a ...

The response of the Typescript Subscription function

I'm struggling with retrieving the subscribe array in NG2. Being new to typescript, I find it difficult to understand how to pass variables between functions and constructors. This is what my code currently looks like: export class RosterPage exten ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

TS2688 Error: Type definition file for 'keyv' is missing

The automated code build process failed last night, even though I did not make any changes related to NPM libraries. The error message I received was: ERROR TS2688: Cannot find type definition file for 'keyv'. The file is in the program because: ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

Strange compilation error encountered with ng-packagr due to Angular @Input inheritance

Encountering a perplexing error message in Angular 7 while working with @Input inheritance. The error message seems illogical because I have 1 mandatory @Input and 2 optional @Input, so things should align... Error: Directive MyComponent, Expected 2 argum ...

The functionality of Angular 2's AsyncPipe seems to be limited when working with an Observable

Encountering an Error: EXCEPTION: Unable to find a support object '[object Object]' in [files | async in Images@1:9] Here's the relevant part of the code snippet: <img *ngFor="#file of files | async" [src]="file.path"> Shown is the ...