I am Naresh
I am Naresh

Reputation: 175

bind the json value in ngmodel in angular 2

This is my json response. How can bind the rewards.rewardName value in [(ngModel)] in angular 2.

 [
  {
   "id": 18,
   "gname": "learning ramayanam",
   "goalCategory": "Education",
   "goalSubCategory": "short-term",
   "goalDesc": "good",
   "rowStatusCode": "D",
   "createID": "1",
   "createTS": null,
   "updateID": "Ram",
   "updateTS": null,
   "rewards": {
     "rewardID": 1,
     "rewardName": "Laptop"
   }
 ]

This is my code buddy how can i bind the value in ngModel

   ngOnInit() {
   this.route.params
        .forEach(params => {
            this.isEdition = !!params['id'];
            if (this.isEdition) {
               // this.getDocument(params['id']);
   this.itemPromise = this.http.get('http://localhost:8080/dy/get-goal?id=' 
    + 
   params['id'])
   .map(res => res.json()).toPromise();

   this.itemPromise.then((item: any) =>  {
   console.log(item);
   var arr = JSON.parse(item);
   this.item = arr[0];
   return item;
   });

Upvotes: 0

Views: 7864

Answers (2)

AVJT82
AVJT82

Reputation: 73357

I would suggest that you take a look at the official http tutorial. I would suggest you use either promises or observables. Seems you would like to use promises, so I'll set up that example for you. Also please consider using a service (like in the tutorial), that is recommended, but here I'll use your existing code:

// remove "this.itemPromise = " and just have the code below
this.http.get('http://localhost:8080/dy/get-goal?id=' + params['id'])
   .toPromise()
   .then(res => res.json())
   .then(data => {
      this.item = data[0];
   })

When this is done, there will be an undefined issue since this is asynchronous. Check this one: Cannot read property "totalPrice" of undefined Two-way-binding, i.e [(ngModel)] doesn't support the safe navigation operator, so you'd want to split this to one-way-binding and ngModelChange:

<input [ngModel]="item?.rewards?.rewardName" 
    (ngModelChange)="item?.rewards?.rewardName ? item.rewards.rewardName=$event : null" > 

Props to this: https://stackoverflow.com/a/36016472/6294072

Here's a DEMO using service, which I suggest you do ;)

Upvotes: 1

argoo
argoo

Reputation: 1476

Parse your json to an object.

var obj = JSON.parse(json);

Then bind it to your element

[(ngModel)]="obj.rewards.rewardName"

Upvotes: 1

Related Questions