0
votes

In my angular 6 project I have a mat-select and I have to use the compareWith function because I am selecting objects.

But at the moment if I don't select anything it seems that the first option is selected, I don't set manually any value in the field and I see the compare function is comparing the first option...and I don't want this behavior. The form correctly still has null value in this field.

Is this an expected behavior or I am missing something?

P.S. I can't add an option like null to my options.

html

<mat-form-field>
  <mat-select (selectionChange)="fareExceptionHandler(); setFareExceptionCode($event)" formControlName="fareException" [compareWith]="displayFn"
  placeholder="{{'ticket.new.labels.fareexception' | translate }}" name="fare">
     <mat-option *ngFor="let fare of fareExceptionsList" [value]="fare">
{{ fare.name }} </mat-option>
   </mat-select>
</mat-form-field>

compare function

  displayFn(model: any) {
    if ((model !== undefined) && (model !== null)) {
      return model.name;
    }
  }

***********************************************EDIT*******************************************

this is a similar example https://stackblitz.com/edit/angular-rykism?file=app%2Fselect-overview-example.ts

1
I tried document.querySelector('select-overview-example').querySelector('mat-select').textContent here on the console of stackblitz.com/angular/… after removing the placeholder, I see an empty string being returned. Can you share a plunker or something, that might really help. - Manit

1 Answers

4
votes

Your compareWith function is wrong. You are using it like the Autocomplete's displayWith function, but it doesn't work that way. It takes two arguments and returns a boolean value. It's main purpose is to find matching options from values applied externally, which happens automatically on initialization, and if you use a form control, the form control's value is used to initialize the select value.

The default implementation returns true when the argument objects are equal. Your implementation returns the name of the first argument object which is an option item. This is truthy so your function ends up matching the first option in the list upon initialization. The second argument is the incoming "set" value which is undefined on initialization (unless your form control has a value).

So your function is essentially saying that undefined is a match for the first option, so the list is selecting the first option at startup. You probably don't need to use compareWith at all, so just get rid of it.