0

I have a weird issue using a . To fill the I have a JSON like this :

values: [{'id' : 'male', 'label' : 'Homme'}, {'id': 'female', 'label' : 'Femme'}]

My HTML looks like this :

<div class="col-md-2" *ngIf="type === 'select'">
    <mat-form-field>
        <select matNativeControl>
             <option *ngFor="let options of values"
                     [value]="options.id"
                     [selected]="options.id == selectedValue">
                {{options.label}}
             </option>
         </select>
        <mat-hint align="end">{{ label }}</mat-hint>
    </mat-form-field>
</div>

If selectedValue is equal to female there is no issue. But if it's equal to male there is no selected option and I can't find why

Any help ?

Thanks

Nathan Cheval
  • 773
  • 2
  • 7
  • 32

2 Answers2

1

I'm not exactly sure what's going on, but I think if you are trying to set a default value on a select this would be helpful Set default option in mat-select.

2 way binding like the link shows or using a reactive form with a value preset are likely your best bets.

Best of luck!

iamaword
  • 1,327
  • 8
  • 17
0

First, you should use here mat-select. Because, if you mat-form-field it is necessary to call a mat-select or any other mat-field there. And then you should use your selectedValue on mat-select's value inside of [(value)] like the following.

<div class="col-md-2" *ngIf="type === 'select'">
    <mat-form-field>
       <mat-select matInput formControlName="yourId" [(value)]="selectedValue"
                    placeholder="Your text">
          <ng-container *ngFor="let options of values">
            <mat-option value="{{options.id}}">{{options.label}}</mat-option>
          </ng-container>
        </mat-select>

    </mat-form-field>

</div>
Abdus Salam Azad
  • 5,087
  • 46
  • 35