0
votes

I have a select options dropdown which contains a list of objects.I'm using ngValue to set the value of the dropdown as an object.However, when the page loads dropdown does not show first object from the list and it shows objects only when I click and open it.

I tried using [selected] property to show preselected option first,I also tried compare function,but it does not seem to work.

<select class="form-control" #selectedValue 
name="selectedValue" id="selectedValue"
 [(ngModel)]="selectedValue[i]" 
(ngModelChange)=onChange($event)>
<option *ngFor="let item of items" [ngValue]="item">
{{item.text}}</option>
</select>

A want to have first option in the dropdown preselected when component is initialized,without having to click on the dropdown

1
Is items just an array of strings?Austin T French
No.It is an array of objectsKKKK

1 Answers

0
votes

your ngMoodel is "selectedValue[i]" .So if you have to preselect a value before opening you need to have a value associated to selectedValue[i].

Try below which is more concise and uses less variables to achieve the same thing:

HTML:

<select class="form-control" [(ngModel)]="selectedValue">
 <option *ngFor="let item of items" [ngValue]={{item.Id}}>
     {{item.text}}
 </option>
</select>

In ts file declare selectedValue with a default value