Santosh
Santosh

Reputation: 3837

angular subscribe custom object and save to localStorage on every input change

I am trying to create food app where I am listing a products. User is able to increase quantity or decrease.

I want to update the object data to localStorage every time the quantity input is updated. Right now I am stuck after creating loop inside ts file.

stackbliz demo

obj = {};
constructor(){}

  cartItems = [
    {id: 1, item_code:"rice_combo", name: "rice combo", price: 95},
    {id: 2, item_code:"chapati_combo", name: "chapati combo", price: 65},
    {id: 3, item_code:"pulses_combo", name: "Pulses combo", price: 25},
  ]

ngOnInit(){
  for(let item of this.cartItems) {
    this.obj[item.item_code] = 0;
  }
}

html component code

<div class="input-group-prepend">
    <button class="btn btn-danger" id="" (click)="obj[item.item_code] = obj[item.item_code] - 1" data-type="minus">-</button>
</div>
<input type="number" name="quant[{{item.id}}]" id="qty_input" class="form-control qty_input"  [(ngModel)]="obj[item.item_code]" value="{{obj[item.item_code]}}" min="1">
<div class="input-group-prepend">
    <button class="btn btn-success" id="" (click)="obj[item.item_code] = obj[item.item_code] + 1" data-type="plus">+</button>
</div>

This is the exact result i get after calling api. This is very short code I have presented in stackbliz. Please help.

output

Upvotes: 1

Views: 442

Answers (2)

Barremian
Barremian

Reputation: 31125

You could pass the object obj in the click event to an handler. Notice I've added onClick(obj) handler to the click event.

<button class="btn btn-danger" id="" (click)="obj[item.item_code] = obj[item.item_code] - 1; onClick(obj)" data-type="minus">-</button>

<button class="btn btn-success" id="" (click)="obj[item.item_code] = obj[item.item_code] + 1; onClick(obj)" data-type="plus">+</button>

And in the controller push it to the local storage

export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  obj = {};

  constructor(){ }

  cartItems = [
    {id: 1, item_code:"rice_combo", name: "rice combo", price: 95},
    {id: 2, item_code:"chapati_combo", name: "chapati combo", price: 65},
    {id: 3, item_code:"pulses_combo", name: "Pulses combo", price: 25},
  ]

  ngOnInit(){
    for(let item of this.cartItems) {
      this.obj[item.item_code] = 0;
    }
  }

  onClick(items) {
    localStorage.setItem('items', JSON.stringify(items));
  }
}

I've modified your Stackblitz

Upvotes: 1

Adrian Sawicki
Adrian Sawicki

Reputation: 708

If you use [(ngModel)] you could add (ngModelChange) and just save your object state to local storage.

Btw. It would be more readable and you would have more options to manipulate data if you move actions like +/- button to their separate functions in your typescript file. Additionally, it's the next place where you could add your local storage state update.

Upvotes: 1

Related Questions