Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular Slide Toggle is always enabled with formControlName attribute

I am trying to use mat slide toggle compoment from Angular Material but, when I try to initialize the slider with a default value with the [checked] attribute, no matter what is in this field the slider is always checked.

<mat-slide-toggle color="primary" [checked]="false" formControlName="{{input.id}}"></mat-slide-toggle>

Any idea ?

Thanks in advance,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Nicolas

>Solution :

Initialize on the form during initialization or go for patchValue instead of using checked.

ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

/**
 * @title Basic slide-toggles
 */
@Component({
  selector: 'slide-toggle-overview-example',
  templateUrl: 'slide-toggle-overview-example.html',
  styleUrls: ['slide-toggle-overview-example.css'],
})
export class SlideToggleOverviewExample {
  isChecked = true;
  formGroup: FormGroup;

  constructor(formBuilder: FormBuilder) {
    this.formGroup = formBuilder.group({
      enableWifi: [true], // <- initialized here
      acceptTerms: [false, Validators.requiredTrue],
    });
    // alternative way -> patchValue ; after the form is initialized and you want to set the values of the slider, you can use patchvalue like so
    this.formGroup.patchValue({enableWifi: true,acceptTerms: false});
  }

  onFormSubmit(formValue: any) {
    alert(JSON.stringify(formValue, null, 2));
  }
}

html

<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>
</form>

stackblitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading