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

What can be done to stop the default route from redirecting to "#/"?

Upon visiting http://localhost/, I have noticed that it automatically redirects me to http://localhost/#/. Is there a way to prevent this redirection and keep the URL at http://localhost/? Furthermore, is it possible to load a default component when the ...

When an attribute is used as a selector for a component in Angular, it can often trigger errors in

Looking to develop a component with an attribute as a selector, here's what I have: @Component({ selector: '[my-attribute-selector]', template: `` }) export class MyComponent { // Some cool stuff } Running into a tslint error t ...

Use Angular mat-table to dynamically insert data by specifying the row index and column index

I am in the process of constructing a table with a response that includes both the number of rows and the number of columns. Within this table, I possess an array of objects that contain a row index number and a column index number, which I am endeavoring ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

How can I encode and decode a base64 string using AngularJS1 and TypeScript?

I am currently working with Angular1 using TypeScript and I have a question that needs some clarification. Within the environment that I am operating in, is there a method available to encode and decode a string in base64? Despite conducting extensive re ...

Ways to inform websocket client of authentication failure

Utilizing the (ws package) in Node.js to handle websockets, I leverage the "on upgrade" event to authenticate incoming clients based on a token provided as a URL parameter. Following the guide here, if the token is invalid/missing/expired, I utilize the fo ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

The function in Angular 5/Typescript disappears when attempting to call it from within another function

After importing D3 into my component, I encounter an issue when trying to assign a layout to the D3.layout property. Strangely, although the layout property is present in the console output of my D3 object, it seems to be unknown when I attempt to call i ...

Retrieve indexedDb quota storage data

I attempted the code below to retrieve indexedDb quota storage information navigator.webkitTemporaryStorage.queryUsageAndQuota ( function(usedBytes, grantedBytes) { console.log('we are using ', usedBytes, ' of ', grantedBytes, & ...

Tips for accurately typing a "Type Mapping" function

In my code, I have a specific type designed for a function that takes one type I as input and returns another type O as output. Here is how it currently looks: export interface IFunctionalMapping<I, O, K extends keyof O> { [prop: Extract<O[K], ...

Connect a click event from one component to another component

Can Angular bind a click event dynamically from a component to another existing component on the page? Check out this image for reference. In my app, I have 4 simple components - a shell component that defines the layout, a header component (blue outline) ...

The NG8002 error has occurred, as it is not possible to connect to 'matDatepicker' because it is not a recognized attribute of 'input'

I've come across an issue while working on my Angular 15 application with Angular Material. I'm trying to incorporate a date picker, but after adding the code snippet below, I encountered an error. <mat-form-field appearance="outline" ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Angular - creating adaptive HTML container with CSS styling

I am trying to achieve a layout similar to the one shown in the image. A container can have multiple elements starting within it or no elements at all. The elements always have a fixed height, and the container's height is determined by the number of ...

Compiling with tsc --build compared to tsc --project

I'm currently working on converting a subproject to TypeScript within my monorepo. Within my npm scripts, I initially had: "build-proj1":"tsc --build ./proj1/tsconfig.json" Although it did work, I noticed that the process was unus ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

Adding an object to a dynamic Akita store containing an Array in an Angular application can be accomplished by following these steps

Currently, I am working on storing dynamic values in an Akita store without the need to create a Model. My challenge lies in adding an object to an existing array within the store. As someone who is new to Akita, my initial approach involved deep cloning ...

Ensuring various conditions with ngIf

I've created a toggle function that updates the text of a link, but I'm struggling to handle multiple conditions. For example, *ngIf="condition1 or condition2". Below is an excerpt from my code: <a routerLink="/ads" class="tip" (click)="togg ...

Ways to exit a forEach loop when a specific condition is satisfied and obtain a string or break statement

I'm currently using Angular 14 and have been encountering some issues with a piece of code involving a ternary operator. Despite researching resources like this one and others, I haven't found a solution that works for me. The code in question lo ...

Adjusting Image Sizes in React using Material-UI: A Guide to Automatically Resizing Images for Various Screen Dimensions

Having trouble making images within my React project responsive across different screen sizes. Using Material-UI, I currently set the maxWidth property with a percentage value which doesn't give me the desired outcome. Seeking advice on a more dynamic ...