If else on "like" button"

I have an animated like button that on click adds the product to the wishlist/favorites

 addToCart(product: Product) {
		console.log(`add ${product.title} to cart`)
		this.cartService.addProduct(product);
	}

This toggles the animation from ‘heart-outline’ to ‘ios-heart’. If you click it again it reverts from ‘ios-heart’ to ‘ios-outline’. All good so far.

What I want to do is remove the product from the wishlist/favorites on second click (if the product is in the cart) using

removeFromCart(product: Product) {
		console.log(`remove ${product.title} from cart`)
		this.cartService.removeProduct(product);
	}

I have a feeling this is fairly simple to do but cannot figure it out. Is there a way using if else in the ts file ?

Sounds like a great plan

Can you share what you have tried to get that done? Especially any issues you have come across implementing the removeProduct method?

At the moment I’m trying to get something like this working. But this both adds and removes the product at the same time!

	addToCart(product: Product) {

		if (this.addToCart !== null) {
		
			console.log(`add ${product.title} to cart`)
			this.cartService.addProduct(product);
		}
		else this.removeFromCart(product) 

			 {
				console.log(`remove ${product.title} from cart`)
				this.cartService.removeProduct(product);
			}
		}

There is a bit of rethinking needed here I’d say…

assuming addToCart is in your component, then this should only deal with adding stuff, not removing… So this is a structural thing you need to address, pending how the method is wired to the UI.

If it is meant to be “toggleInOutCart”, then I suggest to rename the method accordingly. Just for everybody’s clarity.

Second, if (this.addToCart.. always resolves to true because this.addToCart is actually itself (the method). What are you trying to test here? If the product is already in cart? Then it is best to ask the cartService to tell you if it is in the cart or not. So a method needed.

I think here some of the problems start and pending how you implemented this.cartService, other issues may arise.

Hope this helps

1 Like

OK thanks. Yes, i realised a rethink was needed but couldn’t get my head around thie issue :slight_smile: I’ll try again with your thoughts in mind!

1 Like