Skip to content

Instantly share code, notes, and snippets.

@Bilkiss
Created January 5, 2022 13:54
Show Gist options
  • Save Bilkiss/0890d53e7c560a084f27103731b57cab to your computer and use it in GitHub Desktop.
Save Bilkiss/0890d53e7c560a084f27103731b57cab to your computer and use it in GitHub Desktop.
import { Component, OnInit } from '@angular/core';
import { StorageService } from '../../services/storage.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
products: any[] = [];
productNames:any = [];
currentProduct: any = {
name: '',
price: 0
};
storageProductList: any = [];
productNameError = false;
productPriceError = false;
constructor(
public storage: StorageService
) { }
ngOnInit(): void {
this.getProducts();
}
getProducts(){
this.products = [
{ 'Pizza' : 200 },
{ 'Rice' : 150 },
{ 'Bread' : 70 }
];
this.products.map( (key, val) => {
this.productNames.push.apply(this.productNames, Object.keys(key));
});
}
onChangeProduct(event: any): void{
const value = event.target.value
this.productNameError = (!value) ? true : false;
this.productPriceError = (parseInt(this.currentProduct.price) < 1) ? true : false;
this.products.map( prod => {
if (Object.keys(prod)[0].includes(value)){
this.currentProduct.price = Object.values(prod)[0];
};
});
}
addProduct(): void{
if (!this.currentProduct.name || this.currentProduct.price == 0) {
this.productNameError = this.currentProduct.name ? false : true;
this.productPriceError = (parseInt(this.currentProduct.price) < 1) ? true : false;
} else {
this.productNameError = false;
this.productPriceError = false;
this.currentProduct.price = parseInt(this.currentProduct.price);
this.storageProductList = this.storage.get('products');
if (!this.storageProductList) {
this.storageProductList = [];
}
this.storageProductList.push({...this.currentProduct});
this.storage.set('products', this.storageProductList);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment