我正在从 API 中提取数据,除非我将我的 JSON 选项数字值绑定(bind)到 [value] 标记中,否则一切正常。看例子:
WORKING(在选项中选择从 API 获取的数据)
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.name">{{ c.name }}</option>
</select> <!-- select with c.name on value -->
NOT WORKING(未选择数据且第一个选项为空)
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension" [value]="c.value">{{ c.name }}</option>
</select> <!-- select with c.value on value -->
JSON 对象:
subdimension = [{'name': 'sub1','value': 2 },
{'name': 'sub2','value': 4 },
{'name': 'sub3','value': 8}]
我想做的是将一个数字值绑定(bind)到一些选择中,然后将它们全部相加,如下所示:
data.from.api.one + data.from.api.two...
编辑:
来自 data.from.api 的组件代码
constructor (public dataService:DataService){
this.dataService.getData().subscribe(datas => {
this.datas = datas;
});
}
getData(){
return this.http.get('https://api.url/').map(res => res.json());
}
datas:Data[];
data = {
from:{api:{one:'',two:'',three:''}}
}
最佳答案
一切正常。我创造了plunker .您需要在请求后设置 ngModel 值。
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension; let i = index" [ngValue]="c">{{
c.name }}</option>
</select>
如果你想要纯数字
<select [(ngModel)]="data.from.api.one" class="form-control">
<option *ngFor="let c of subdimension; let i = index" [value]="c.value">{{
c.name }}</option>
</select>
在您的代码中,在 ngOnInit Hook 中使用此代码
return this.http.get('https://api.url/').map(res => res.json()).do((d) => {
this.subdimension = d;
//if you use object
this.data.from.api.one = d[0]
//if you use value
this.data.from.api.one1 = d[0].value
})
或
this.dataService.getData().subscribe(datas => {
this.datas = datas;
this.data.from.api.one = datas[0]
//if you use value
this.data.from.api.one1 = datas[0].value
});
关于json - 下拉列表无法从对象中提取数字值(Angular 4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225316/