Use various onChange functions for sliding toggle

I need assistance with a toggle app I'm developing that includes two slide toggles. Even though I have separate onChange() methods for each toggle, toggling one slide-toggle also changes the value of the other slide toggle. The toggle state is saved in a database. Can someone please help me resolve this issue? Thank you in advance.

Below is the TypeScript code:

export class PolicyComponent implements OnInit {

  @Output() change: EventEmitter<MatSlideToggleChange>;
  formGroup: FormGroup;
  policy1: boolean=false;
  policy2: boolean=false;

  disable:boolean=true;
  serverData:any
  constructor(
    private formBuilder: FormBuilder,private policyService:PolicyService
  ) { }

  ngOnInit() {
  
  // Code to retrieve data from the server

    this.formGroup = this.formBuilder.group({
      Policy1:new FormControl( this.policy1,[]),
      Policy2: new FormControl( this.policy2,[])

    });

}

  onFormSubmit() {
  
   // Function to handle form submission and update serverData
  
  }

  onChange(ob: MatSlideToggleChange) {
    this.policy1 = !this.policy1;
    this.disable=false;
  }

  onChange1(ob: MatSlideToggleChange) {
    this.policy2 = !this.policy2;
    this.disable=false;
  }
}

This is my template:

<form class="example-form" [formGroup]="formGroup" (ngSubmit)="onFormSubmit()" ngNativeValidate>
  <mat-action-list>
    <mat-list-item > <mat-slide-toggle       
      (change)="onChange($event)"  [checked]="policy1"  formControlName="Policy1" >Policy1</mat-slide-toggle></mat-list-item> 
    <mat-list-item > <mat-slide-toggle  (change)="onChange1($event)" [checked]="policy2" formControlName="Policy2">Policy2</mat-slide-toggle></mat-list-item>

  </mat-action-list>
  <p>Form Group Status: {{ formGroup.status}}</p>

  <button mat-raised-button [disabled]="disable" type="submit">Save Settings</button>
</form>

Answer №1

When dealing with mat-slide-toggle elements, having double bindings can confuse Angular, leading to ambiguity in assigning values.

<mat-action-list>
   <mat-list-item > 
      <mat-slide-toggle (change)="onChange($event)"  
      [checked]="policy1" <----------------------------------first binding
      formControlName="Policy1"><----------------------------second binding
      Policy1</mat-slide-toggle>
   </mat-list-item> 
   <mat-list-item > 
      <mat-slide-toggle (change)="onChange1($event)" 
      [checked]="policy2" <----------------------------------first binding
      formControlName="Policy2"><----------------------------second binding
      Policy2</mat-slide-toggle>
   </mat-list-item>
</mat-action-list>

In practice, this issue commonly arises. The recommended approach for using reactive forms in Angular is to utilize two-way binding via the property formControlName="...". When constructing the form, follow these guidelines:

ngOnInit() {
    this.formGroup = this.formBuilder.group({
        Policy1: new FormControl(false, []),
        Policy2: new FormControl(false, [])
    });
    this.policyService.getPolicy().subscribe((response) => {
        this.serverData = response[0];
        this.formGroup.controls.Policy1.setValue(this.serverData.policy1=="F");
        this.formGroup.controls.Policy2.setValue(this.serverData.policy2=="F");
    });
}

Update your HTML as shown below:

<mat-action-list>
   <mat-list-item > 
      <mat-slide-toggle (change)="onChange($event)"  
      formControlName="Policy1"><----------------------------Only!!
      Policy1</mat-slide-toggle>
   </mat-list-item> 
   <mat-list-item > 
      <mat-slide-toggle (change)="onChange1($event)" 
      formControlName="Policy2"><----------------------------Only!!
      Policy2</mat-slide-toggle>
   </mat-list-item>
</mat-action-list>

Answer №2

Below is the solution to your inquiry

  <mat-card class="result">
  <mat-card-content>
    <h2 class="example-h2">Result</h2>

    <section class="example-section">
      <mat-slide-toggle
          [(ngModel)]="checked1"
          class="example-margin"
          [color]="color"
          (change)="changed()">
        Slide me! {{checked}}
      </mat-slide-toggle>

    </section>
     <mat-slide-toggle
          [(ngModel)]="checked2"
          class="example-margin"
          [color]="color"
          (change)="changed2()">
        Slide me! {{checked}}
      </mat-slide-toggle>
  </mat-card-content>
</mat-card>

This is the TypeScript code snippet

  export class SlideToggleConfigurableExample {
  color = 'accent';
  checked1 : boolean=true;
  checked2:boolean=false;
  disable:any;

  changed(){
  //  this.checked1 = !this.checked2;
    this.checked1=true;
  }
  changed2(){
    // this.checked1 = !this.checked2;
    this.checked2=false;
  }
}

View Stackblitz Demo

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

One method I use to retrieve ajax data and assign it before rendering the view

Despite putting the ajax.get in the created function, I am still unable to retrieve the ap_name value. This issue is related to vue.js created: function () { ajax.get('/envs').then(function (res) { this.apName = res.AP_NAME; ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

The Lerna command for adding packages fails with an error message stating that the packages are not related

Currently, I am utilizing lerna to manage a multirepo containing interrelated packages. This issue only arose after installing a new operating system. Whenever I attempt to utilize lerna add to add a dependency from one package to another, an error occurs ...

Are there any additional features available in NetSuite that allow for viewing multiple pages within a PDF document?

I'm looking to compile a list of all available pick tickets and then consolidate them into a single PDF file. Unfortunately, I am only able to generate one page per ID. var transactionFile = render.pickingTicket({ entityId: 501, printMode: render.Pri ...

Error: The code is unable to access the '0' property of an undefined variable, but it is functioning properly

I am working with two arrays in my code: bookingHistory: Booking[] = []; currentBookings: any[] = []; Both arrays are populated later in the code. The bookingHistory array consists of instances of Booking, while currentBookings contains arrays of Booking ...

Unwillingness of Ajax to accept Names containing apostrophes as a parameter

$(".loadingPnl").removeClass('hdn'); var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl; var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/S ...

I encountered a problem while trying to install Angular Material within my Nx workspace

Currently in the process of setting up an Angular and React project within a Nx monorepo workspace. Encountering trouble while attempting to install Angular Material using npm i @angular/material I'm running Angular v16. Below is the specific error me ...

Invalid Syntax: The token '21' is found unexpectedly at column 12 in the expression [2013-08-28 21:10:14] beginning at [21:10:14]

I'm in the process of creating a straightforward directive for a date countdown. However, I've hit a roadblock with this particular error: Syntax Error: Token '21' is an unexpected token at column 12 of the expression [2013-08-28 21:10 ...

ASP.NET can have issues with the functionality of jQuery AJAX

I'm currently working on an asp.net webform project and I'm looking to implement jQuery ajax functionality. Below is the code snippet I have so far: <asp:Button ID="btn_comment" runat="server" CssClass="contact_btn pull-right" Text="send" OnC ...

Steps for constructing an object literal with a property designated as the `keyof` type

Struggling to articulate my question, here is a simplified code snippet outlining what I aim to accomplish. class Example<T, TId extends keyof T> { public create(id: T[TId]): T { return { [TId]: id, // Encounter an error at this point. Ob ...

Retrieving data using ngxs selector for displaying nested JSON data

My issue is related to the user object that contains nested arrays, making it difficult to access secondary arrays. I have created selectors with ngxs to retrieve and utilize data in HTML code, but extracting secondary arrays seems impossible. { "us ...

"Mastering the art of displaying real-time data on a thermometer using D3.js

Welcome to the sample code for a thermometer created using D3.js. You can view the code on jsfiddle. I've developed a web page displaying a dynamic thermometer with values updating every second. Here's the function: setInterval(function(){ getN ...

Error with Angular PWA: A fatal error has occurred as the module '@schematics/angular/utility' cannot be located

Trying to execute the command below has been giving me trouble: ng add @angular/pwa Every time I run it, an error pops up saying: An unhandled exception occurred: Cannot find module '@schematics/angular/utility' I attempted to install @schemati ...

What is the process for displaying the attributes of a custom object in Typescript?

I need help returning an array of prop: value pairs for a custom object using the myObject[stringProp] syntax. However, I keep encountering this error message: TS7053: Element implicitly has an 'any' type because expression of type 'str ...

Setting the default value to null or 0 in a Select dropdown in Angular 7

There is a select dropdown code that may be hidden in some instances. When the select dropdown is hidden, I want to ensure null or 0 is sent instead of an empty value when saving the form. How can I achieve this? <div class="col-md-4" [hidden]="!cpSe ...

I am consistently running into an Uncaught Syntax error within my Express server.js while using Angular 1.5.6

I've been struggling for hours to integrate Angular with routes that I've created. Eventually, I decided to give Express a try and set up a basic server.js file to run as a standalone server. However, nothing seems to be working and I keep encou ...

Tips on transforming a JSON file into a response for my personal server

After successfully converting an Excel file to JSON format using my code, I encountered a challenge when trying to convert this as a response. Despite attempting to use res.send in the JS code, it only displayed directory/inner codes instead of a response. ...

What is the best approach for extracting functions from express routes for unit testing?

I have a JavaScript controller containing some exported routes. I am interested in accessing the functions used within these routes for unit testing purposes. While many blogs suggest creating actual HTTP requests to test express routes, I consider this t ...

Access any nested node within a JSON/JS object by specifying the key's value

After spending hours searching on various forums for a solution to my problem, I have yet to find one that directly addresses the issue I am facing. So, please take a moment to review the details below. The object structure in question is as follows: let ...

Utilize the most recent impacted information stored within an object

When I return this list object, it includes: return ({ name: data.name, request: { method: methodLine[index].method.toUpperCase(), header: data.request.header, description: data.request.description, }, response: [ { ...