|
|
|
@@ -1,4 +1,7 @@ |
|
|
|
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; |
|
|
|
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; |
|
|
|
import { NgForm } from '@angular/forms'; |
|
|
|
import { Subscription } from 'rxjs/Subscription'; |
|
|
|
|
|
|
|
import { Ingredient } from '../../shared/ingredient.model'; |
|
|
|
import { ShoppingListService } from '../shopping-list.service'; |
|
|
|
|
|
|
|
@@ -7,18 +10,52 @@ import { ShoppingListService } from '../shopping-list.service'; |
|
|
|
templateUrl: './shopping-edit.component.html', |
|
|
|
styleUrls: ['./shopping-edit.component.css'] |
|
|
|
}) |
|
|
|
export class ShoppingEditComponent implements OnInit { |
|
|
|
@ViewChild('nameInput') nameInputRef: ElementRef; |
|
|
|
@ViewChild('amountInput') amountInputRef: ElementRef; |
|
|
|
export class ShoppingEditComponent implements OnInit, OnDestroy { |
|
|
|
@ViewChild('f') shoppingListForm: NgForm; |
|
|
|
subscription: Subscription |
|
|
|
editMode = false; |
|
|
|
editedItemIndex: number; |
|
|
|
editedItem: Ingredient; |
|
|
|
|
|
|
|
constructor(private shoppingListService: ShoppingListService) { } |
|
|
|
|
|
|
|
ngOnInit() { |
|
|
|
this.subscription = this.shoppingListService.startedEditing.subscribe( |
|
|
|
(index: number) => { |
|
|
|
this.editedItemIndex = index; |
|
|
|
this.editMode = true; |
|
|
|
this.editedItem = this.shoppingListService.getIngredient(index); |
|
|
|
this.shoppingListForm.setValue({ |
|
|
|
name: this.editedItem.name, |
|
|
|
amount: this.editedItem.amount |
|
|
|
}) |
|
|
|
} |
|
|
|
); |
|
|
|
} |
|
|
|
|
|
|
|
onSubmit(form: NgForm) { |
|
|
|
const value = form.value |
|
|
|
const newIngredient = new Ingredient(value.name, value.amount); |
|
|
|
if (this.editMode) { |
|
|
|
this.shoppingListService.updateIngredient(this.editedItemIndex, newIngredient); |
|
|
|
} else { |
|
|
|
this.shoppingListService.addIngredient(newIngredient); |
|
|
|
} |
|
|
|
this.editMode = false; |
|
|
|
form.reset(); |
|
|
|
} |
|
|
|
|
|
|
|
onClear() { |
|
|
|
this.shoppingListForm.reset(); |
|
|
|
this.editMode = false; |
|
|
|
} |
|
|
|
|
|
|
|
onDelete() { |
|
|
|
this.shoppingListService.deleteIngredient(this.editedItemIndex); |
|
|
|
this.onClear(); |
|
|
|
} |
|
|
|
|
|
|
|
onAddItem() { |
|
|
|
const newIngredient = new Ingredient(this.nameInputRef.nativeElement.value, |
|
|
|
this.amountInputRef.nativeElement.value); |
|
|
|
this.shoppingListService.addIngredient(newIngredient); |
|
|
|
ngOnDestroy() { |
|
|
|
this.subscription.unsubscribe(); |
|
|
|
} |
|
|
|
} |