简体   繁体   中英

How to select/deselect all options when I select 'All' option in Angular 12?

I have one array with the label 'All' like below. Created the mat-option based on the array.

  1. If I select 'All' means its needs to be selected for all other options.
  2. If I deselect the 'All' option means deselecting all options from the dropdown.

component.html:

<mat-form-field>
  <mat-select [ngModel]="selectedCities" placeholder="Favorite City" multiple>
    <mat-option *ngFor="let city of allCities" [value]="city.value">
      {{city.label}}
    </mat-option>
  </mat-select>
</mat-form-field>

component.ts:

selectedCity: any;

  allCities = [
    { label: 'All' },
    { value: 'Mumbai-1', label: 'Mumbai' },
    { value: 'Delhi-2', label: 'Delhi' },
    { value: 'Chennai-2', label: 'Chennai' },
    { value: 'Kolkatta-3', label: 'Kolkatta' },
  ];

Just check this Demo Might Help as you need to check and uncheck the checkbox at once

https://stackblitz.com/edit/select-all-option-angular-material?file=src%2Fapp%2Fapp.component.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM