angular - 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!
解决方案
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
推荐阅读
- php - 如何将后值发送到两个单独的函数
- perl - Perl:处理多个非阻塞套接字(服务器)
- reactjs - 服务器上的 ReactJS 日期验证失败 - Symfony4 Azure/nginx
- javascript - JavaScript:更快的轮盘选择
- scipy - 计算两个样本的累积分布
- javascript - 引导下拉按钮单击后消失
- java - 在构造函数测试类中使用来自 mockito-junit-jupiter 的 MockitoExtension 进行空模拟
- ruby - 使嵌入资源的 route_param 成为字符串
- c# - 无法安装 Nuget Microsoft.AspNet.Web.Optimization,+1 其他包
- html - 边距底部对 iOS CSS 没有影响