Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

angular - 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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...