Getting the values from a multi select with ngModel and ngModelChange not working

1.2k Views Asked by At

I am trying to wrap my head around ngModel ngModelChange. The multi select returns an array of selections that I want to concat into a single string. I can't seem to be able to grab the values from the multi select. the mobileChange() function returns the array with undefined inside, which is equal to the number of selections. i.e. ['undefined', 'undefined'] if two options were selected.

How do I get the values?

Template HTML

<mat-form-field>
  <mat-label>Mobile Access Type</mat-label>
  <mat-select id="mobileAccessType" [(ngModel)]="tempMobile" (ngModelChange)="mobileChange()" required multiple>
    <mat-option ngDefaultControl *ngFor="let option of mobileAccessTypes"  >{{option.value}}</mat-option>
  </mat-select>
</mat-form-field>

Component TS

  public tempMobile = ['stuff'];

  public mobileChange(): void {
      console.log('CHANGES', this.tempMobile);
  }
1

There are 1 best solutions below

0
On

Inside your mobileChange function you should send the $event as a parameter:

(ngModelChange)="mobileChange($event)"

Then in your TS you get the values

public mobileChange(e): void {
    this.tempMobile.push(e.toString());
}

https://stackblitz.com/edit/angular-ngmodelchange-pau?file=app/app.component.ts