Event in (selectionChange) returns error Cannot read properties of undefined (reading 'value')

Viewed 95

I have built a mat-select that looks like this in the template:

<mat-form-field>
  <mat-select (selectionChange)="setActualYear($event)">
    <mat-option *ngFor="let actualYears of navService.actualYearsDropdown" [value]="actualYears">
       {{ actualYears }}
     </mat-option>
   </mat-select>
 </mat-form-field>

For the change I have built the following function:

/**
   * Function for set the year in actual years dropdown
   * @param event any
   */
  setActualYear(event: any): void {
    this.year = this.navService.year = parseInt(event.target.value, 10); // Error occurs here
    localStorage.setItem('setYearForUserNavigation', `${this.year}`);
    this.navService.sendNavEventUpdate('yearChanged');
  }

Do you know how I can solve the problem?

1 Answers

Believe that the event is MatSelectChange type.

To get the value, you need to use event.value instead of event.target.value.

import { MatSelectChange } from '@angular/material';

setActualYear(event: MatSelectChange): void {
  this.year = this.navService.year = parseInt(event.value, 10); // Error occurs here
  ...
}
Related