Guide on utilizing mat-slide-toggle to assign either a value of 1 or 0

I am utilizing the mat-slide-toggle feature from Material in a similar manner to this example https://material.angular.io/components/slide-toggle/overview

The problem I am encountering is similar to the issue outlined in this link:

https://stackblitz.com/edit/angular-zafcmh-rvgjhs?file=app%2Fslide-toggle-configurable-example.ts

When I click on any one switch, I only want that particular switch to be affected, not all of them simultaneously.

Could you please suggest a possible solution?

Here is my HTML code snippet:

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

And here 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)
      this.hsP.activatehomeboxp(editHomeboxp).subscribe(
        result => {
          if (result === true) {
            Materialize.toast('HomeboxPacket updated successfully', 4000);

          } else {
            this.loading = false;
          }
        },

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

Thank you for your assistance!

Answer №1

Make sure to include device: any = [] in your controller and assign a value to device[i] instead of just device.

Check out this live demonstration for guidance here

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

Steps to dynamically include a marker on a Google Maps component using HTTPGET in Angular 6

I am currently working on an Angular 6 application that involves integrating the Google Javascript API with AGM. So far, the map functions well except for dynamically adding markers using an http get request. Here is a snippet of the component.html: < ...

Guide to inserting an Angular routerLink within a cell in ag-Grid

When attempting to display a link on a basic HTML page, the code looks like this: <a [routerLink]="['/leverance/detail', 13]">A new link</a> However, when trying to render it within an ag-Grid, the approach is as follows: src\ ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

Switch from flexbox layout to begin on the next column within the same row

I am attempting to create a CSS layout where, after a specific element like :nth-child(6), the elements will break and form a separate column within the same row. The parent element should split into 2 columns after every 6th element in the same row, then ...

Incorporate any enum value into a Typescript interface

I'm working with a Typescript interface export interface MyInterface { valid: boolean; resourceType: MyEnum; message: string; } As well as an enum enum MyEnum { 'a', 'b', 'c' } Is there a way to allow the ...

Please provide either a string or an object containing the proper key for TypeScript

Within my project, the languageSchema variable can either be a string or an object containing the 'Etc' key. The corresponding interface is defined as follows: let getLanguageSchema = (language: string): string => languagesSchemas[language]; ...

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

A layout featuring nested buttons and links within a card element, utilizing the power of Link in NextJs

After extensive searching on S.O., I have been unable to find a solution that works flawlessly. The issue at hand involves a card component in a NextJs application that is encompassed within a <Link> tag. Additionally, there is another <Link> t ...

typescriptWhat is the syntax in TypeScript for creating a prototype of a multidimensional

I'm currently working on implementing additional methods for a 2D array using TypeScript. Adding methods to a 1D array is straightforward, as shown below: interface Array<T> { randomize(); } Array.prototype.randomize = function () { ...

Adjust property value based on changes in a related property

Currently, I am developing a TypeScript-powered Angular (5) application and I have encountered a puzzling question that is proving elusive to solve. Let me illustrate with the following example: ... export class SomeComponent implements onInit { ... ...

Retrieving JSON data in Angular 5 returns a 400 bad request error

Having trouble calling the REST API of Amazon S3 from Angular 5. Keep getting a 400 bad request error. This problem has been persisting for a while now and I really need to find a solution or at least get some suggestions on where the issue might be. Her ...

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 ...

Unable to trigger an event from an asynchronous method in TypeScript

In my scenario, I have a child component that needs to emit an event. However, I require the parent handler method to be async. The issue arises when the parent does not receive the emitted object in this particular configuration: Parent Component <co ...

Use the mat-slide-toggle to switch up the text style

Is it possible to apply different text styles using Ang-Material-2's mat-slide-toggle? https://i.stack.imgur.com/WM9FC.jpg <mat-slide-toggle [color]="primary" [checked]="true">Slide me</mat-slide-toggle> <h3>Text</h3> ...

Oops! There seems to be an issue with Angular - I'm getting an

I need to retrieve JSON data from the server and only display it on the web page after clicking a button. However, I encounter an error after the first click: core.js:4352 ERROR TypeError: Cannot read property 'imie' of undefined at HttpTestC ...

Configuring environment variables during Jest execution

A variable is defined in my `main.ts` file like this: const mockMode = process.env.MOCK_MODE; When I create a test and set the variable to true, it doesn't reflect as `'true'` in the main file, but as `'false'` instead. describe ...

Looping through child components in Angular 2 to extract values from their content

Attempting to iterate through child components within a parent component in Angular 2 as shown below: <segment-header> </segment-header> <segment-content *ngFor="let content of listContent"> </segment-content> Where listContent is ...

Ways to verify the input label in Angular version 4 and above?

I'm working on an Angular component that includes a form structured like this: <form> <label for="Name">Click me</label> <input type="text" id="Name" name="Name" /> <label for="Name2">Click me 2</label> &l ...

Exploring the possibilities of Ionic 2 with Web Audio API

I am encountering issues while using the Web Audio API with Ionic 2. Despite my efforts, I keep running into errors. It seems that the problem lies within the TypeScript compiler. I attempted to resolve it by adding "es2015.promise", but to no avail. The e ...

Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this: const nestedArray = [ [{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }], [{ id: 4 }, { id: 5 }, { id: 6 }], ] In the case where objects with id 1 and 2 are already grou ...