javascriptangularangular2-formbuilder

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,

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