The mat-slide-toggle updates the values for all products, with each value being unique

In my app, I am using Material slide-toggle to control the activation status of products. However, I am facing the following issues:

  1. Whenever I toggle one product, it affects the values of all other products as well.
  2. The displayed value does not match the set value. Refer to the console screenshot for details.

https://i.stack.imgur.com/bsvoc.png

https://i.stack.imgur.com/0gek7.png

For reference:

When active is set to 1 --> The function submits. When active is set to 0 --> The function activates the slide-toggle.

This is a snippet of my HTML code:

<form [formGroup]="activeHomeboxPForm">
        <mat-slide-toggle formControlName="active" id="active" [(ngModel)]="active" (change)="onChange($event)" (click)="onActiveHomeboxP(item.homeboxpackage_id)">
        </mat-slide-toggle>
        {{active}}
      </form>

And this is my TypeScript code:

   this.activeHomeboxPForm = this.fb.group({
      'active': new FormControl('', Validators.required),
      'homeboxpackage_id': new FormControl('', Validators.required)
    });

populateFormHomeboxP() {
    this.activatedRoute.params.subscribe(
      params => {
        this.hsP.getHomeboxPById(params['id']).subscribe(
          homeboxP => {
            this.homeboxP = homeboxP;
            this.activeHomeboxPForm.controls['active'].setValue(homeboxP.active);
            this.activeHomeboxPForm.controls['homeboxpackage_id'].setValue(homeboxP.homeboxpackage_id);
          }
        );
      }
    );
  }

  onActiveHomeboxP(homeboxpackageid) {
    this.loading = true;
    if (confirm('Are you sure to change Status?')) {

      let editHomeboxp = new HomeboxP(
        this.activeHomeboxPForm.value
      );
      editHomeboxp.homeboxpackage_id = homeboxpackageid;
      console.log(editHomeboxp) // --> active: 1
      this.hsP.activatehomeboxp(editHomeboxp).subscribe(
        result => {
          if (result === true) {
            Materialize.toast('HomeboxPacket updated successfully', 4000);
            this.router.navigate(['/main/homeboxpackage']);
          } else {
            this.loading = false;
          }
        },

        error => {
          this.loading = false;
        }
      );
    }
  }
  onChange(value) {
    if (value.checked === true) {
      this.active = 1;
      console.log(1);  //1
    } else {
      this.active = 0;
      console.log(0); //0
    }
  }

Answer №1

perhaps this solution may be beneficial

HTML:

<ng-container matColumnDef="inventory_qtd">
      <th mat-header-cell *matHeaderCellDef> Sales </th>
      <td mat-cell *matCellDef="let products">
        <div *ngIf="products.status === 1">
          <mat-slide-toggle [checked]="true" (change)="onChange($event, products.id)">Available</mat-slide-toggle>
        </div>
        <div *ngIf="products.status === 0">
          <mat-slide-toggle [checked]="false" (change)="onChange($event, products.id)">Not Available</mat-slide-toggle>
        </div>

      </td>
    </ng-container>

Code:

onChange(value, product_id) {
if (value.checked === true) {
  this.active = 1;
  console.log({ checked: true, product_id: product_id});
} else {
  this.active = 0;
  console.log({ checked: false, product_id: product_id});
}}

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

Inquiry on SSGHelpers and GetStaticProps functionality with parameterization

I am currently implementing createProxySSGHelpers to prefetch data using trpc in a project I'm developing, but I'm facing an issue where the id from the url params is returning as undefined even though it's visible in the url bar. Below is ...

Error encountered during installation of Nativescript Post Install Script

While I am comfortable running one of our current projects with Nativescript, I encountered an error when attempting to install it on a new project using the following command: sudo ng new --collection=@nativescript/schematics the-juice-box --shared The ...

The Clarity Design side menu becomes unscrollable when the content is too long for the view

Currently, I am facing an issue with the sidenav where the navigation links go beyond the view and I am unable to scroll to see the "hidden" links unless I zoom out. My frontend framework is Angular 5 and this is how I organized the components: <nav c ...

Explore the Ability to Monitor Modifications to an Object's Property in Angular2/Typescript

Can we track changes to an object's field in Angular2/Typescript? For instance, if we have a class Person with fields firstName, lastName, and fullName, is it feasible to automatically modify fullName whenever either firstName or lastName is altered? ...

The program encountered an issue: it cannot access the property 'invalid' because it is undefined

I have a scenario where I am utilizing nested FormGroup in Angular, with the parent formGroup in the HTML and skills as the nested form. However, during validation, the controls are not being found. Can anyone provide assistance with thi ...

Adding existing tags to Select2 in Angular2 can be accomplished by following these steps:

HTML: <select data-placeholder="Skill List" style="width:100%;" class="chzn-select form-control" multiple="multiple"> <option *ngFor="#skill of allSkills" [ngValue]="skill">{{skill}} </option> </select> TS: allSkills = [& ...

The setter of the computed property is failing to execute

Currently, I am working with a computed property that represents an object of a specific type defined within my Vuex Store. The goal is to utilize this property in my component using v-model. I have thoroughly set up getters and setters for this property a ...

Defining Array Types in TypeScript JSON

My attempt at coding a class in TypeScript has hit a roadblock. Whenever I try to utilize Jsons in an Array, the system crashes due to a TypeScript error. Here's the class I tried to create: class Api { url: string | undefined; credentials: Ar ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

Common mistakes made while working with decorators in Visual Studio Code

Having trouble compiling TypeScript to JavaScript when using decorators. A persistent error message I encounter is: app.ts:11:7 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the ' ...

Error in Angular 4: No service available for MatDialogRef in Angular Material (webpack)

I have attempted various methods and followed the documentation instructions to set up Angular Material. Upon checking my console, I encountered the following error: core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for MatDialogRef ...

Downloading videos from WebRTC getDisplayMedia in Angular 8 is not supported

Currently utilizing the NPM package in conjunction with Angular 8 found here: [ https://www.npmjs.com/package/webrtc-adapter ] to mimic the WebRTC getDisplayMedia functionality showcased here: [ ] I have successfully managed to initiate and terminate a r ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Create a global variable by importing an external module in TypeScript

I am currently developing a TypeScript npm module called https://www.npmjs.com/package/html2commonmark. This module is versatile and can be utilized in nodejs (via require) as well as in the browser (by loading node_modules/html2commonmark/dist/client/bund ...

Steps for modifying the value of a field within an Angular formGroup

Is there a way to update the value of the "send_diagnostic_data" field in a separate function? private generateForm(): void { this.messageForm = new FormGroup({ message: new FormControl(''), date: new FormControl(new Date()), messag ...

Building upon the foundation: Extending a base component in Angular

I have a Base Component that is extended by its children in Angular. However, when creating a new Component using angular-cli, it generates html and css files that I do not need for the base component. Is there a way to create a Base Component without inc ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

Angular 2 experiencing issues with the authorization header

Hello there! I am currently working with the Ionic 2 framework alongside Angular, and I'm facing an issue while trying to make an HTTP request with the authorization header. It seems like the header is not being sent properly. Can someone help me iden ...

`Angular 6 and the expiration of Jwt tokens`

I am currently developing an angular application that utilizes jwt for authenticating database calls. However, I encountered a problem where, when the token expires on the server, the app starts displaying blank pages instead of the expected data. This hap ...