1

I have a select field as follows:

<select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states" 
      [ngValue]="state">
       {{state.name}}</option>
</select>

However, as I'm reusing the same component, I would like my option to be set to a value if my ngModel has a value. For example, if myClient.address has myClient.address = {"name":"Texas", "stateId":"2"}, I want Texas to be the selected option.

How do I achieve this?

  • Possible duplicate of [two way binding with elvis-operator](http://stackoverflow.com/questions/36016407/two-way-binding-with-elvis-operator) – eko Feb 16 '17 at 05:56
  • @echonax Does not help. – Sreeraag Mohan Feb 16 '17 at 05:58
  • Seems you also need `compareFn` mentioned in http://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular-2/35945293#35945293. For `ngModel` on ` – Günter Zöchbauer Feb 16 '17 at 05:59
  • thin link may help you http://stackoverflow.com/questions/35978450/angular-2-dropdown-options-default-value/41180705#41180705 – Anil Samal Feb 16 '17 at 06:07
  • Check this [**answer**](http://stackoverflow.com/questions/43008374/how-to-set-the-initial-value-in-a-dropdown-in-angular2-for-a-different-object/43008690#43008690) – Aravind Mar 29 '17 at 06:43

1 Answers1

1
<select class="form-control" [ngModel]="myClient.address?.name" name="state" (ngModelChange)="getCitiesByState($event)">
   <option class="form-control" *ngFor="let state of states" 
      [ngValue]="state">
       {{state.name}}</option>
</select>

Now if myClient.address has myClient.address = {"name":"Texas", "stateId":"2"}, I want Texas to be the selected option.

All the changes you need is [ngModel]="myClient.address?.name" add ? , that defines optional behaviour , so if its provided then it will get selected and if not then it will work as there is nothing selected.

But here you have to provide atleast myClient.address with value or without value.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122