Need some help. I have a product catalog and shopping cart on similar page, and I want to show item in the cart when "Buy" button will be pressed. When button is pressed the item goes to localStorage and it appears in shopping cart only after F5. I think I should use Input decorater, but how to implement it? Maybe the right way is to use services and observables but I weak at angular for now to do it. Also need to remove item from cart, I shoul rewrite localstorage for that, right?
catalog
<div class="content">
<div class="item" *ngFor="let auto of auto; let i=index">
<div> <img src="../../assets/db/{{auto.photo}}" alt=""></div>
<div class="text">
<p>{{auto.name}} - {{auto.price}} руб.</p>
<p><input type="submit" value="Купить" (click)="toCart(i)"></p></div>
</div>
auto: any;
cart=[];
price=[];
constructor(private service:DataService) { }
ngOnInit() {
this.getItems();
}
getItems(){
this.service
.getItems()
.subscribe(goods => {
this.auto = goods;
} )
}
toCart(i){
this.cart.push(this.auto[i]);
this.price.push(this.auto[i].price);
localStorage.setItem("cart",JSON.stringify(this.cart));
localStorage.setItem("price",JSON.stringify(this.price));
}
cart component
export class CartComponent implements OnInit {
list = localStorage.getItem("cart");
names = JSON.parse(this.list);
len = this.names.length;
price = this.names.price;
Message: string;
constructor() { }
ngOnInit() {
}
send(){
this.Message = "Готово";
localStorage.setItem('cart',JSON.stringify(""));
}
// remove(i){
// let newlist = this.names.slice(this.names[i],1);
// console.log(newlist);
// this.len = this.names.length - 1;
// }
}
cart template
<div class="content">
<li *ngFor="let name of names; let i=index">
<p>{{name.name}} - {{name.price}}руб.</p>
<button (click)="remove(i)">Удалить</button>
<!-- <button (click)= "add(i)">Добавить </button> -->
</li>
<p>Количество: {{len}} </p>
{{Message}}
<p><input type="submit" value="Оформить заказ" (click)="send()"></p>