Search code examples
angulartypescriptangular-materialangular5

How to implement select all in angular material drop down angular 5


I am using mat-select to display drop down, I need select all functionality in angular drop down.

Below is my html

<mat-select formControlName="myControl" multiple (ngModelChange)="resetSelect($event, 'myControl')">
    <mat-option>Select All</mat-option>
    <mat-option [value]="1">Option 1</mat-option>
    <mat-option [value]="2">Option 2</mat-option>
    <mat-option [value]="3">Option 3</mat-option>
</mat-select>

Here is my ts code

/**
 * click handler that resets a multiple select
 * @param {Array} $event current value of the field
 * @param {string} field name of the formControl in the formGroup
 */
protected resetSelect($event: string[], field: string) {
    // when resetting the value, this method gets called again, so stop recursion if we have no values
    if ($event.length === 0) {
        return;
    }
    // first option (with no value) has been clicked
    if ($event[0] === undefined) {
        // reset the formControl value
        this.myFormGroup.get(field).setValue([]);
    }
}

Some how its not working properly, kindly help or let me any better way to do this.


Solution

  • Use click event try this

    <mat-form-field>
      <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
        <mat-option [value]="1" (click)="selectAll(ev)"   
        #ev
         >SelectAll</mat-option>
        <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
      </mat-select>
    </mat-form-field>
    
    }
    

    Typescript:

    selectAll(ev) {
        if(ev._selected) {
            this.toppings.setValue(['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato']);
            ev._selected=true;
        }
        if(ev._selected==false) {
          this.toppings.setValue([]);
        }
    }
    

    Example:https://stackblitz.com/edit/angular-czmxfp