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.
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.
disableOptionCentering: boolean. Whether to center the active option over the trigger. @Input() disableRipple: boolean. Whether ripples are disabled.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With