Search code examples
angular-materialangular7

Select all mat option does not work properly


Following this question I have:

<mat-select [formControl]="tipoAttivitaSelect" multiple >
              <mat-option #selectAll [value]="0" (click)="all()">
                  All
                 </mat-option>
            <mat-option *ngFor="let attivita of mappaAttivita" [value]="attivita" (click)="opzioneSelezionata(attivita.value)">
              {{attivita.description}}
            </mat-option>
          </mat-select>

And in .ts

@ViewChild('selectAll') private selectAll: MatOption;
tipoAttivitaSelect: FormControl = new FormControl();
mappaAttivita =  [{
      value:"option1",
      description:"Option 1"
  },
  {
      value:"option2",
      description:"Option 2"
  }]

   ngOnInit(){
    this.selectAll.select();
    this.tipoAttivitaSelect.patchValue([...this.mappaAttivita.map(item => item), 0])
  }



all() {
    if (this.selectAll.selected) {
      this.tipoAttivitaSelect.patchValue([...this.mappaAttivita.map(item => item), 0])
    } else {
      this.tipoAttivitaSelect.patchValue([])
    }
  }

What I expect is that when I go to the page they are all selected, but it doesn't happen. When I enter the page there is only the "all" option selected, but the others are not; then if I uncheck the all option and then check it back, all the options are selected correctly.
I don't get why it happens, since I do the same operation both in ngOnInit and in the method "all()"


Solution

  • You have to do the select all in the ngAfterViewInit because you trigger the all() function before your mat-select has loaded the values. Thats because in the angular life cycle the values of the mat select are only loaded after the view got initialized.