angular-materialmat-selectmat-form-fieldmat-option

Selected option is undefined - Angular material


I want to know from a list which options the user selected. In both ways the event/the object is undefined. What is the best way to do it?

My first way:

<mat-form-field>
    <mat-select [(value)]="selectedUserType" multiple (selectionChange)="filterByCustomFields()">
        <mat-option *ngFor="let custom of filteredRows" [value]="custom.value">
            {{custom.fieldHebKey}}
        </mat-option>
    </mat-select>
</mat-form-field>

And the second:

<mat-select [formControlName]="'customField'" multiple (selectionChange)="filterByCustomFields($event)">
    <mat-option *ngFor="let custom of filteredRows" [value]="custom.value">
        {{custom.fieldHebKey}}
    </mat-option>
</mat-select>
</mat-form-field>

Solution

  • Using reactive forms the second option is usually a better way.

    Make sure you have assigned the filteredRows with the fieldHebKey and value property, if the value property is missing you might get a null or undefined value.

    And instead of using selectionChange you can listen to value changes event of the form control in ngOnInit

    filteredRows = [
      {fieldHebKey: 1, value: 'one'},
      {fieldHebKey: 2, value: 'two'},
      {fieldHebKey: 3, value: 'three'}
    ]
    
    ngOnInit(){
      this.formGroup.get('customField').valueChanges.subscribe(val => {
        console.log(val)
      })
    }