1
votes

I am passing an object to my Angular component and trying to get the dropdown to show the already selected value when the dropdown is rendered. At my current code, the dropdown only shows the first option. I passed in the value of the 2nd dropdown option.

In my ts code, the object.reason.code is a string of value 'EX2'

the dropdown list is binded to

reasons ReasonList = [{name: 'EX1', code: "EX1'},  {name: 'EX2', code: "EX2'}, {name: 'EX3', code: "EX3'}]

Here is my html

<mat-select [(ngModel)]="object.reason.code"   [formControl]="myCtrl" required>
  <mat-option *ngFor="let reason of reasons" [value]="object.reason.code">{{reason.name}}</mat-option>
</mat-select>

THe desired behavior, the dropdown is blank if object.reason.code is undefind else if the string is EX2, the dropdown should display the EX2 option.

Whatever I selected, the change should be reflected in the object.reason.code

I tried changed [(ngModel)] to [(value)] but nothing is working.

I looked up the following post and followed the steps but no success

Angular Material: mat-select not selecting default

Any help is appreciated.

1
you don't need to use ngModel and formControl , I have give an idea about an option for default value ,check my answer hope this will work for you 👍malbarmavi

1 Answers

1
votes

with ngModel just declare a variable and set the value base on the list values (code) and I just put an empty string as default value

component

ReasonList = [{name: 'EX1', code: "EX1'},....] ;

object = { reason : { code : 'EX1' } }; // 👈 set default value to EX1

template

<mat-select [(ngModel)]="object.reason.code"  required>
  <mat-option [value]="''"> Unselected </mat-option> 
  <mat-option *ngFor="let reason of reasons" [value]="object.reason.code">
      {{reason.name}}
   </mat-option>
</mat-select>

demo