2
votes

I have work with angular 4 and use material newest. When I use md-select with multiple select options but I want have a opiton "Select All" will select all option to exist. What do I do?

<md-select multiple>
<md-option> Select All </md-option>
<md-option> Option 1 </md-option>
<md-option> Option 2 </md-option>
<md-option> Option 3 </md-option>
</md-select>
2
I have just stumbled over the exact same problem. setValue() doesn't seem to check the boxes, so I'm currently taking a look at this approach: stackoverflow.com/questions/47183007/…masterfloda

2 Answers

0
votes

I added checkbox inside the mat-select and i changed the design to look like part of the mat-select

TS: @ViewChild('select') select: MatSelect;

 onAllChanged(checked: any) {
    if (checked) {
       this.select.value = //add all your choices 
     } else {
        this.select.value = [];
     }
 }

 selectionchanged() {
    if (this.selectedValues.length === yourlist.length) {
      this.allchecked = true;
    } else {
      this.allchecked = false;
    }
 }    

HTML:

<mat-form-field>
  <mat-select #select="matSelect"
    (selectionChange)="selectionchanged()" [(ngModel)]="selectedValues" multiple>
       <mat-checkbox  [(ngModel)]="allchecked"
         (change)="onAllChanged($event.checked)" style="padding-left:15px;">
                 All
       </mat-checkbox>
       <mat-option>option1<mat-option>
       <mat-option>option2<mat-option>
       <mat-option>option3<mat-option>
   </mat-select>    
</mat-form-field>
-1
votes

I came up with a callback on the value change of the select, which then checks if the first selected option has no value and then resets the formControl (this solution is for reactive forms. It should be easy to adapt for model forms)

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>

TS:

/**
 * 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([]);
    }
}

This works, but it feels a bit dirty. setValue() of course triggers ngModelChange, so we would go into a recursion, which I simply stop with $event.length === 0. Also, checking for the first option with a value of undefined seems a bit ... meeeeh...

I would appreciate if someone could provide a more elegant solution!