How to enable and disable slide toggle in angular material

Viewed 8349

I have generated list of mat slide toggle's using for loop, but what want is, when I click on one slide toggle other slide toggles should be disabled.

my code:

HTML:

     <div class="row">
        <div class="col-md-6 mt-2" *ngFor="let data of attributes">
              <mat-slide-toggle>{{data}}</mat-slide-toggle>
        </div>
    </div>

TS:

   attributes = ["Last 7 days", "Last 30 days", "Last 60 days"]

In this scenario, when I click on "Last 7 days" slide toggle, then "Last 30 days", "Last 60 days" should be disabled,

2 Answers
  1. Change your attributes array to hold objects with the attribute and a property for the disabled state. E.g. options = [{id: 1, title: "Last 7 days", disabled: false}, ...]; Add an id to identify which one was toggled.

  2. Bind the disabled property to the disabled input and the id to the id attribute.

  3. See the API Docs and use @Output() change: EventEmitter<MatSlideToggleChange> event to call a function which iterates over your array and set all disabled flags to true except the one which triggered the event.

  4. Do the same thing for enabling all toggles.

  <div *ngFor="let data of options">
    <mat-slide-toggle 
       [id]="data.id" 
       [disabled]="data.disabled" 
       (change)="disableAll($event)">
        {{data.title}}
    </mat-slide-toggle>
  </div>

  options = [
    { id: 1, title: "Last 7 days", disabled: false },
    { id: 2, title: "Last 30 days", disabled: false },
    { id: 3, title: "Last 60 days", disabled: false }
  ];

  disableAll(ev: MatSlideToggleChange) {
    if (ev.checked) {
      this.options
        .filter(opt => opt.id != ev.source._elementRef.nativeElement.id)
        .forEach(opt => (opt.disabled = true));
    } else {
      this.options.forEach(opt => (opt.disabled = false));
    }
  }

Here's a demo: https://stackblitz.com/edit/angular-fhmsyp?file=src%2Fapp%2Fslide-toggle-overview-example.ts

 <mat-slide-toggle color="primary"
        place
        [(ngModel)]="disalbeShipping"></mat-slide-toggle>
    <mat-form-field appearance='outline'
        validationMessageContainer>
        <mat-label>Tax Shipping Rate</mat-label>
        <input matInput
            placeholder=''
            formControlName=''
            required
            [disabled]="disalbeShipping">
    </mat-form-field>
Related