-1

I am working on angular app. I have some mat-toggle in my code. Code is as follows:

<form
  class="example-form"
  [formGroup]="formGroup"
  (ngSubmit)="onFormSubmit(formGroup.value)"
  ngNativeValidate
>
  <mat-slide-toggle formControlName="enableWifi">Enable Wifi</mat-slide-toggle>
  <mat-slide-toggle formControlName="acceptTerms"
    >Accept Terms of Service</mat-slide-toggle
  >

  <p>Form Group Status: {{ formGroup.status}}</p>

  <button mat-rasied-button type="submit">Save Settings</button>
  <button mat-rasied-button type="submit">Activate All</button>
</form>

Stackblitz:

stackblitz.com/edit/mat-slide-toggle-example-guurez?file=app%2Fslide-toggle-overview-example.html

I have one button Activate All. If user clicks this button all the mat-toggle gets enabled and on and text of button is changed to Deactivate All and vice versa. In case if user goes and disable one toggle, again this button is changed to Activate ALL and on click of this button all toggle should be enabled and on and button should be set to Deactivate all and so on. How can I do that?

Roma
  • 39
  • 2
  • 8

1 Answers1

0

I added plenty of console logs and methods to showcase various way of reacting to changes and how to dynamically change text on the button or how to toggle all switches on/off.

https://stackblitz.com/edit/mat-slide-toggle-example-gkulzg?file=app%2Fslide-toggle-overview-example.ts

But basically you have to update two things. Form is one of them and the toggle switches are the other things. Updating form doesn't necessarily mean toggle values are changed and the other way around - unless you tie them together.

There is room for improvement here. For example methods could be concatenated and instead of calling separate methods to turn true/false you could just use != to turn booleans and so on.

<button mat-rasied-button (click)=onActivateAll() *ngIf="!isWifiToggled || !isTermsToggled">Activate All</button>
  onActivateAll() {
    console.log('activate all')
    this.formGroup.setValue({
      enableWifi: true, 
      acceptTerms: true
    });
    this.isWifiToggled = true;
    this.isTermsToggled = true;
    this.formGroup.updateValueAndValidity();
  }
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33