0

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()"

Usr
  • 2,628
  • 10
  • 51
  • 91
  • 1
    You have to do the select all in the ngAfterViewInit because you trigger the `all()` function before your mat-select has loaded the values. – JuNe Oct 11 '19 at 05:24
  • Hi @JuNe thanks. If you answer the question I'll choose it as solution – Usr Oct 11 '19 at 08:01

1 Answers1

1

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.

JuNe
  • 1,911
  • 9
  • 28