You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

65 regels
1.9 KiB

  1. import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
  2. import { NgForm } from '@angular/forms';
  3. import { Subscription } from 'rxjs/Subscription';
  4. import { Store } from '@ngrx/store';
  5. import { Ingredient } from '../../shared/ingredient.model';
  6. import { ShoppingListService } from '../shopping-list.service';
  7. import * as ShoppingListActions from '../ngrx/shopping-list.actions';
  8. @Component({
  9. selector: 'app-shopping-edit',
  10. templateUrl: './shopping-edit.component.html',
  11. styleUrls: ['./shopping-edit.component.css']
  12. })
  13. export class ShoppingEditComponent implements OnInit, OnDestroy {
  14. @ViewChild('f') shoppingListForm: NgForm;
  15. subscription: Subscription
  16. editMode = false;
  17. editedItemIndex: number;
  18. editedItem: Ingredient;
  19. constructor(private shoppingListService: ShoppingListService,
  20. private store: Store<{shoppingList: {ingredients: Ingredient[]}}>) { }
  21. ngOnInit() {
  22. this.subscription = this.shoppingListService.startedEditing.subscribe(
  23. (index: number) => {
  24. this.editedItemIndex = index;
  25. this.editMode = true;
  26. this.editedItem = this.shoppingListService.getIngredient(index);
  27. this.shoppingListForm.setValue({
  28. name: this.editedItem.name,
  29. amount: this.editedItem.amount
  30. })
  31. }
  32. );
  33. }
  34. onSubmit(form: NgForm) {
  35. const value = form.value
  36. const newIngredient = new Ingredient(value.name, value.amount);
  37. if (this.editMode) {
  38. this.shoppingListService.updateIngredient(this.editedItemIndex, newIngredient);
  39. } else {
  40. this.store.dispatch(new ShoppingListActions.AddIngredient(newIngredient));
  41. }
  42. this.editMode = false;
  43. form.reset();
  44. }
  45. onClear() {
  46. this.shoppingListForm.reset();
  47. this.editMode = false;
  48. }
  49. onDelete() {
  50. this.shoppingListService.deleteIngredient(this.editedItemIndex);
  51. this.onClear();
  52. }
  53. ngOnDestroy() {
  54. this.subscription.unsubscribe();
  55. }
  56. }