spottedmahn
spottedmahn

Reputation: 16011

setting initial value using ngModel for select dropdown

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 returning the value is not selected in the dropdown.

From other readings, I've learned this is b/c the objects are not the same instance. What do I do in this situation then?

<select name="tranType"
    class="form-control"
    [(ngModel)]="model.tranType"
    required>
   <option *ngFor="let tranType of tranTypes"
     [ngValue]="tranType">{{tranType.desc}}</option>
 </select>

Solution

ngOnInit(): void {
    this.myService.getTranTypes()
        .subscribe(tranTypes => {
            this.tranTypes = tranTypes;
            //set value of tranType if already set in the model
            if (this.myService.model.tranType != undefined) {
                this.myService.model.tranType = this.tranTypes.find(r => r.id == this.myService.model.tranType.id);
            }
        },
        error => this.errorMessage = <any>error);
}

Upvotes: 2

Views: 4558

Answers (3)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657546

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.

Upvotes: 1

Aravind
Aravind

Reputation: 41573

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

Upvotes: 3

Bruno Jo&#227;o
Bruno Jo&#227;o

Reputation: 5545

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.

Upvotes: 1

Related Questions