Selected option is undefined - Angular material

403 views Asked by At

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>
1

There are 1 answers

0
Mr. Stash On BEST ANSWER

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)
  })
}