Angular 2 - Update a total from one model when updating another model

80 views Asked by At

I have two services, a ShopService, and a PersonService.

The ShopService contains an array of fruits like this:

fruits = [
  {
    name: 'apple'
    quantity: 25
  },
  {
    name: 'banana',
    quantity: 25
  }
];

The PersonService contains people, and all the fruit they've bought from the shop.

people = [
  {
    name: 'fred',
    fruits: [{ name: 'apple', quantity: 2 }, { name: 'banana', quantity: 3}]
  },
  {
    name: 'wilma',
    fruits: [{ name: 'apple', quantity: 1}, { name: 'banana', quantity: 0}]
  }
];

Now when I open a form for a person, I want to be able to see the total remaining number of each fruit in the shop, and validate the fruit quantity inputs accordingly.

If the quantity is bound with ngModel, how can I make the remaining total update instantly? I don't want to update the quantity in the shop, but rather sum all the fruits that the people have, and minus that from the shop value to display.

0

There are 0 answers