setting initial value using ngModel for select dropdown

一世执手 提交于 2019-11-28 14:23:36

From 4.0.0-beta.6 on, you can use a custom comparison function

<select [compareWith]="equals"
equals(o1: Country, o2: Country) {
   return o1.id === o2.id;
}

for earlier versions you can look up the tranType in tranTypes by comparing content similar to above equals, and then assign the found instance to model.tranType to make it the selected one.

You should have the value binded to the ngModel exactly same as that of your object inside array.

<select [(ngModel)]="model.tranType">
 <option *ngFor="let type of tranTypes" [ngValue]="type.id">{{type.Desc}}</option>
</select>

Best advisable to use id property as ngValue.

LIVE DEMO

You must place the variable model.tranType inside a service that are loaded by a model that loads the two models you are navigating between. This way you will end up with a singleton service and the variable will be persisted while you are using your site. The problem in this approach is that if you refresh the page the service will be restarted and you will have the default option sleected again. To solve this, you must save the model.tranType variable state in localStorage, so even when closing the browser the option will remain the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!