Search code examples
angularangular-ngmodel

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);
}

Solution

  • 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.