Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 742
kunal Avatar asked Aug 28 '18 16:08

kunal


People also ask

How do you limit Angular materials multiple select items to n items?

In your component create a global variable named mySelections . This will store your selections :) It will hold an array of strings. Change the number 3 to N and presto, you're done.

What is disableOptionCentering?

disableOptionCentering: boolean. Whether to center the active option over the trigger. @Input() disableRipple: boolean. Whether ripples are disabled.


1 Answers

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

like image 78
Chellappan வ Avatar answered Nov 14 '22 22:11

Chellappan வ