-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshopping-list-edit.component.ts
65 lines (55 loc) · 1.75 KB
/
shopping-list-edit.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Component, OnInit, OnDestroy, ViewChild } from "@angular/core";
import { Ingredient } from "../../models/ingredient.model";
import { ShoppingService } from "../../services/shopping.service";
import { NgForm } from "@angular/forms";
import { Subscription } from "rxjs";
@Component({
selector: "app-shopping-list-edit",
templateUrl: "./shopping-list-edit.component.html",
styleUrls: ["./shopping-list-edit.component.css"]
})
export class ShoppingListEditComponent implements OnInit, OnDestroy {
subscription: Subscription;
editMode: boolean = false;
editedItemIndex: number;
editedItem: Ingredient;
@ViewChild("f") shoppingListForm: NgForm;
constructor(private shoppingService: ShoppingService) {}
ngOnInit() {
this.subscription = this.shoppingService.startedEditing.subscribe(
(index: number) => {
this.editMode = true;
this.editedItemIndex = index;
this.editedItem = this.shoppingService.getIngredientByIndex(index);
this.shoppingListForm.setValue({
name: this.editedItem.name,
amount: this.editedItem.amount
});
}
);
}
onUpsertItem(form: NgForm) {
const value = form.value;
const name = value.name;
const amount = value.amount;
const ingredient = new Ingredient(name, amount);
if (this.editMode) {
this.shoppingService.updatedIngredient(this.editedItemIndex, ingredient);
} else {
this.shoppingService.addIngredient(ingredient);
}
this.editMode = false;
form.reset();
}
onClear() {
this.shoppingListForm.reset();
this.editMode = false;
}
onDelete() {
this.shoppingService.deleteIngredient(this.editedItemIndex);
this.onClear();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}