I am doing a udemy course on angular and came across this code. I have a sample project which has a Add item button which adds a new item in the array and displays the updated array on screen.
shopping-edit.component.ts
export class ShoppingEditComponent implements OnInit {
@Input() ingredientsArray : Ingredient[];
shoppingItemName : string = 'Test';
shoppingItemAmount : number = 66;
constructor(private shoppingListService : ShoppingListService) { }
ngOnInit() {
}
onItemAdd(){
console.log(this.shoppingItemName)
this.shoppingListService.addIngredient(this.shoppingItemName, this.shoppingItemAmount);
}
}
I have an event emitter which emits the updated array when the "add" button is clicked.
shopping-list.service.ts
ingredientsChanged = new EventEmitter<Ingredient[]>();
addIngredient(name: string, value : number){
this.ingredients.push(new Ingredient(name, value));
this.ingredientsChanged.emit(this.ingredients.slice());
}
To display the list, I am using shopping-list.component.ts
export class ShoppingListComponent implements OnInit {
constructor(private shoppingListService : ShoppingListService){}
ingredients : Ingredient[];
ngOnInit() {
this.ingredients = this.shoppingListService.getIngredients();
this.shoppingListService.ingredientsChanged.subscribe(
(ingredients : Ingredient[]) => {
this.ingredients = ingredients;
}
)
console.log("hello")
}
}
Since ngOnInit() of shopping-list.component.ts runs only once, how is the updated list getting displayed every time the "add" button is clicked?