A popup window cannot output a numeric value from an object (Angular 4)

I pull data from an API that works fine if I don't bind the value of my JSON parameter number to the [value] tag. see example:

WORK (data obtained from the API is selected in the option)

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

DOES NOT WORK (data not selected, and the first option is zero)

<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 object:

subdimension = [{'name': 'sub1','value': 2  },
  {'name': 'sub2','value': 4 },
  {'name': 'sub3','value': 8}]

What I want to do is bind a numeric value to some select items, and then sum them up as:

data.from.api.one + data.from.api.two ...

EDIT:

Component code from 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:''}}
}
+4
source share
1 answer

Everything is working. I created a plunker . You need to set the ngModel value after the request.

<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
});
0

Source: https://habr.com/ru/post/1685699/


All Articles