下拉列表无法从对象中提取数值(Angular 4)

时间:2017-09-14 17:41:02

标签: json angular typescript

我从API中提取数据,除非我将JSON选项号值绑定到[value]标记,否则这样做会很好。见例子:

工作(在选项中选择了从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 -->

不工作(未选择数据且第一个选项为空)

<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}]

我想要做的是将数字值绑定到某些选择中,然后将所有这些值相加如下:

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:''}}
}

1 个答案:

答案 0 :(得分:0)

一切正常。我创建了plunker。您需要在请求后设置upUp 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
});