首页 > 解决方案 > Why does select dropdown show empty default in Angular 8 after http call?

问题描述

I have written a basic html to display array elements in drop down, while default value to be shown is fetched from an http service in ngOnInit. But i get to see the default value in drop down as empty value.

This is my Html:

<select class="form-control" name="chocolate"
   [(ngModel)]="selectedChocolateId">
   <option *ngFor="let chocolate of chocolates" [ngValue]="chocolate.id">
   {{chocolate.name}}
   </option>
</select>

And this is my Typescript code:

public selectedChocolateId:number;

ngOnInit() {
    this._chocolateService.GetChocolateId().subscribe(data => {
        this.selectedChocolateId = data;
    })
  }

public chocolates = [
  { id:1, "name":"Diary Milk"},
  { id:2, "name":"Five star"}
];

When i run the code, i get an empty default value in drop down. But when i console log, i get to see the fetched value from service. Thanks in advance!

标签: angulartypescriptangular8

解决方案


Most probably data is not of type number and therefore it cant find the right value.

https://stackblitz.com/edit/angular-twhj6x

Just add a Number() around data


推荐阅读