setting initial value using ngModel for select dropdown

前端 未结 3 1282
灰色年华
灰色年华 2020-12-12 03:53

I have an array of tranTypes (transaction types) that are loaded into a dropdown. After the user selects a value and navigates to another component upon return

相关标签:
3条回答
  • 2020-12-12 04:14

    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.

    0 讨论(0)
  • 2020-12-12 04:21

    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.

    0 讨论(0)
  • 2020-12-12 04:27

    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

    0 讨论(0)
提交回复
热议问题