Array reinitializes on push()

25 Views Asked by At

I have a shopping list array of ingredient objects stored in the parent component. The child component lets me input the arguments for a new ingredient and send it to the parent on a button click.

For some reason after the received object is pushed into the array, it briefly appears in the DOM but quickly the app reloads and the object disappears as and the array is reinitialized to contain default objects.

Child template:

<input type="text"
       id="name"
       class="form-control"
       #nameInput/>  

<input type="number"
       id="amount"
       class="form-control"
       #amountInput/>

<button class="btn btn-success"
        type="submit"
        (click)="onAddIngredient()"
        >
            Add
</button>

The child component launches an output event as it should and emits a new ingredient object with entered argument values:

export class ListEditComponent {
  @ViewChild('nameInput') nameInputRef!: ElementRef;
  @ViewChild('amountInput') amountInputRef!: ElementRef;

  @Output() ingredientAdded = new EventEmitter<Ingredient>();

  onAddIngredient() {

    const ingName = this.nameInputRef.nativeElement.value;
    const ingAmount = this.amountInputRef.nativeElement.value

    const newIngredient = new Ingredient(ingName, ingAmount);
    this.ingredientAdded.emit(newIngredient);
  }
}

The parent component:

export class ShoppingListComponent implements OnInit {
  ingredients: Ingredient[] = [
    new Ingredient('Apples', 5),
    new Ingredient('Tomatoes', 5),
  ];

  ngOnInit() {

  }

  onIngredientAdded(newIngredient: Ingredient) {
    this.ingredients.push(newIngredient);
  }
}

In the parent template the list is generated using *ngFor:

<app-list-edit (ingredientAdded)="onIngredientAdded($event)"></app-list-edit>
    <hr />
    <ul class="list-group">
      <a
         class="list-group-item"
         style="cursor: pointer"
         *ngFor="let ing of ingredients"
         >
        {{ ing.name }} ({{ ing.amount }})

      </a>
    </ul>
0

There are 0 best solutions below