Ascena
Ascena

Reputation: 60

Angular6/Typescript - Add Object into Array of another Array

I need to push an Object into an array which contains another array by writing the ID into a textfield.How to use methods with arrays in arrays?

Demo: https://angular-flj24f.stackblitz.io

Classes:

 class Food {
    id: number;
    name: string;
    preis: number;
    art: string;
}

class Foodplan {
    id: number;
    foodPerWeek: number[] = new Array(5);

Thanks in advance.

Upvotes: 0

Views: 417

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30999

In the stackblitz, it looks like the foodPlan array has only one element, which has index 0. To add to the list of foods in that element, you would do something like this:

this.foodPlan[0].essenProWoche.push(id);

See this updated stackblitz. In the future, if you add a control to add multiple elements to the foodPlan array, then you'll need to know which one you are adding the food to and use the appropriate index.

Upvotes: 1

Related Questions