1
votes

I'm working with a select component that have ngx-mat-select-search, and I want to set a default value selected when I call the component, but it don't show it and I can't see any error on console. I don't know what's happening, what I'm missing?

Here's the StackBlitz

https://stackblitz.com/edit/angular-hre1qd

Here's also the main code I use for put a default value:

test.component.html

<mat-form-field [formGroup]="formData" class="prueba">
    <mat-select formControlName="valueSelect"  #singleSelect>
        <mat-option>
            <ngx-mat-select-search [formControl]="inputFilter" [placeholderLabel]="'Search...'"
                 [noEntriesFoundLabel]="'Not Found...'">
                <i class="mdi mdi-close menu-icon" ngxMatSelectSearchClear></i>
            </ngx-mat-select-search>
        </mat-option>
        <mat-option value='-1' selected>{{defaultValue}}</mat-option>
        <mat-option *ngFor="let data of controlFilter | async" [value]="data[dataValue]">
            {{ data[dataShow] }}
        </mat-option>
    </mat-select>
</mat-form-field>

test.component.ts

setInitialValue() {
    this.controlFilter.next(this.dataSource.slice());
    this.formData
      .get("valueSelect")
      .setValue(this.dataSource[2]);
    // WHY IS NOT CHANGING TO A DEFAULT VALUE
  }

Thanks in advise!!

2

2 Answers

1
votes

That's because you need to pass only code instead of the whole object:

.setValue(this.dataSource[2].code);

Forked Stackblitz

1
votes

You are assigning whole object to 'valueSelect', to auto-populate option , you only need to pass a reference here code is unique it can be used, by which defaultValue will be auto-populated

Try this

  setInitialValue() {
    this.controlFilter.next(this.dataSource.slice());
    this.formData
      .get("valueSelect")
      .setValue(this.dataSource[2].code); //here based on formControl value that having same code; that obj name field will be displayed/populated in selected option
  }

You may use <mat-option value='-1' selected>{{defaultValue}}</mat-option> to display/select empty option, if not needed kindly remove this line code.