Allowing The User To Add Ingredients To The Shopping List

You might also like

You are on page 1of 2

Allowing the User to Add Ingredients to the Shopping List

-We'll be using local reference @ViewChild for now

1. In shopping-edit.component.html
In our input Element, we have added the below local references

#nameInput
#amountInput

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


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

In the add button


We added click event listener and a method which will be definining later

<button class="btn btn-success" (click) = "onAddItem()">Add</button>

2. In shopping-edit.component.ts

it will get a value by using @ViewChild()


then we pass in our our input reference
create a property with a type of ElementRef module from @angular core

@ViewChild('nameInput') nameInputRef: ElementRef;


@ViewChild('amountInput') amountInputRef: ElementRef;

then we crated an event and store in a property.


name: string, amount: number is not a value but just a type definition.

@Output() ingredientAdded = new EventEmitter<{name: string, amount: number}()>

or instead of using type definition of our Ingredient model, we simply


use our Ingredient class from our Ingredient Model.

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


We added our Output() decorator, also imported it.

Then we import our Ingredient Model


import { Ingredient } from '../../ingredient.model';

Then we defined our onAddItem() {} method

*******************
onAddItem() {
const ingName = this.nameInputRef.nativeElement.value;
const ingAmount = this.amountInputRef.nativeElement.value;
const newIngredient = new Ingredient(ingName, ingAmount);
this.ingredientAdded.emit(newIngredient);

3. in shopping-list.component.html
we listen to our (ingredientAdded) event, we called the function here and pass
$event
so we can get the event thrown by our event.

**************

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

4. in our shopping-list.component.ts

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

You might also like