Set initially selected item in Select list in Angular2

后端 未结 7 1131
独厮守ぢ
独厮守ぢ 2020-12-07 23:59

I\'ve managed to get a Select list to bind with my model for the purpose of saving, but I cannot work out how to make Angular2 automatically select the correct option on the

相关标签:
7条回答
  • 2020-12-08 01:02

    Okay, so I figured out what the problem was, and the approach I believe works best. In my case, because the two objects weren't identical from a Javascript perspective, as in: they may have shared the same values, but they were different actual objects, e.g. originalObject was instantiated entirely separately from objects which was essentially an array of reference data (to populate the dropdown).

    I found that the approach that worked best for me was to compare a unique property of the objects, rather than directly compare the two entire objects. This comparison is done in the bound property selected:

    <select [ngModel]="originalObject">
        <option *ngFor="let object of objects" [ngValue]="object" [selected]="object.uniqueId === originalObject.uniqueId">{{object.name}}</option>
    </select>
    
    0 讨论(0)
提交回复
热议问题