0

I have a Recipe model which contains an array of Flavors.

export class Flavor {
    name: string;
    base: Base;

    removeFlavor(flavor: Flavor) : void {
        for (let f in this.flavors) {
            if (this.flavors[f][0] == flavor) {
                delete this.flavors[f];
            }
        }
    }
}

export class Recipe {
    strength: number;
    flavors: [Flavor, number][];
}

I'm trying to bind these variable number of flavors to inputs which can be dynamically added and removed from the recipe. Is there a feature in Angular 2 that supports this? Here is what I have so far:

<h3>Flavors</h3>

<div *ngFor="let flavor of mix.recipe.flavors" class="flavor">
    <label>Name</label>
    <input type="text" [(ngModel)]="flavor[0].name">

    <label>Strength <i>(percent)</i></label>
    <input type="number" [(ngModel)]="flavor[1]" min="0" max="1" step=".00001">

    <label>Base</label>
    <label *ngFor="let base of bases; let value = index;">
        {{ base }}
        <input type="radio" [checked]="value === flavor[0].base" (click)="flavor[0].base = value">
    </label>

    <a href="#" (click)="mix.recipe.removeFlavor(flavor)">Remove Flavor</a>
</div>

<a href="#" (click)="/* create new flavor */">New Flavor</a>

Remove Flavor should remove the Flavor from the Mix and also remove the entire div.flavor associated with it. New Flavor should create a new Flavor in Mix and append a new, bound div.flavor to the end of the list.

Shane
  • 1,190
  • 15
  • 28
  • I don't get what the problem is or the question is about. With `(click)="xxx(...)"` you get `xxx()` called and there you can remove the item from `flavors`. `*ngFor` then also automatically removes the `
    `.
    – Günter Zöchbauer Dec 12 '16 at 06:14
  • @GünterZöchbauer when putting `mix.recipe.removeFlavor(flavor)` in the click event, it removes the flavor from the recipe object but not the markup. – Shane Dec 12 '16 at 06:32

1 Answers1

1

Use splice() instead of delete

See also Deleting array elements in JavaScript - delete vs splice

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567