Alter the button's operation when clicked

I am looking for some guidance on my project. I have a button in my application that allows users to add a movie to their watchlist. My goal is to change the functionality of this button to "remove from watchlist" when it is pressed. How can I achieve this? Do I need to update a Boolean value in the database or implement something on the front-end?

You can access the source code here.

Below is the code snippet for my watchlist component:


@Component({
  selector: 'app-watchlist',
  templateUrl: './watchlist.component.html',
  styleUrls: ['./watchlist.component.css'],
})
export class WatchlistComponent {
  watchlist: IMovie[] | null = [];

  constructor(private auth: AuthService, private api: ApiService) {
    this.getWatchlist();
  }

  getWatchlist() {
    this.api.loadUserWatchlist().subscribe({
      next: (v) => {
        this.watchlist = v;
        console.log(this.watchlist);
      },
    });
  }
}

At this point, I have not attempted any solutions yet.

Answer №1

I've made some updates to your watchlist.component.ts file. Additional explanations are provided below the code snippet.

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { ApiService } from 'src/app/api.service';
import { IMovie } from 'src/app/shared/interfaces/movie';
import { MovieService } from 'src/app/movie/movie.service';

@Component({
  selector: 'app-watchlist',
  templateUrl: './watchlist.component.html',
  styleUrls: ['./watchlist.component.css'],
})
export class WatchlistComponent {
  watchlist: IMovie[] | null = [];
  isAddedToWatchlist: boolean = false;

  constructor(private auth: AuthService, private api: ApiService, private movieService: MovieService) {
    this.getWatchlist();
  }

  getWatchlist() {
    this.api.loadUserWatchlist().subscribe({
      next: (v) => {
        this.watchlist = v;
        console.log(this.watchlist);
      },
    });
  }

  toggleWatchlist(movieId: number) {
    if (this.isMovieInWatchlist(movieId)) {
      this.movieService.removeFromWatchlist(movieId).subscribe(() => {
        this.isAddedToWatchlist = false;
      });
    } else {
      this.movieService.addToWatchlist(movieId).subscribe(() => {
        this.isAddedToWatchlist = true;
      });
    }
  }

  isMovieInWatchlist(movieId: number): boolean {
    return this.watchlist ? this.watchlist.some((movie) => movie.id === movieId) : false;
  }
}

I introduced a new property called isAddedToWatchlist to track whether the current movie is in the user's watchlist or not.

A method named toggleWatchlist(movieId: number) was added, triggered when the user clicks either the "Add to Watchlist" or "Remove from Watchlist" button. This function will call the appropriate add or remove methods from the MovieService, updating the isAddedToWatchlist flag accordingly.

Included is the

isMovieInWatchlist(movieId: number): boolean
method to determine if a specific movieId is in the user's watchlist. This helps decide which text to display on the button - "Add to Watchlist" or "Remove from Watchlist."

To utilize these changes in your component's HTML template, you can bind the Angular (click) event to trigger the toggleWatchlist(movieId) method upon button click. Moreover, employ Angular's data binding alongside *ngIf to dynamically display either "Add to Watchlist" or "Remove from Watchlist" based on the isAddedToWatchlist value.

Lastly, here's an example of the HTML button:

<button (click)="toggleWatchlist(movie.id)">
  {{ isMovieInWatchlist(movie.id) ? 'Remove from Watchlist' : 'Add to Watchlist' }}
</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Parsing JSON data into an object within a component.ts file

I'm facing a challenge with converting JSON data into object format to perform a create operation. json [ { "user": { "id": 83, "username": "das", "first_name": "dsafha", "last_name": "dfksdfk", "email" ...

Set up a Pinia store with a specific data type

Note: I am a beginner in JavaScript I am currently working on synchronizing an object with a Pinia store and a Python REST API. My goal is to define a type just once without having to duplicate it in the store. export const useTicketStore = defineStore(&a ...

Troubleshooting problem with handling Angular modules

I'm currently working on effectively organizing folders in my Angular application. Specifically, I've set up a /components directory for shared components and a /pages directory for page-specific components. Each directory has its own module but ...

Utilizing Angular 4 with the highcharts gauge feature

I am currently utilizing angular 4 (4.4.4), "highcharts": "~6.0.1", "angular2-highcharts": "~0.5.5". The simple chart is displaying correctly, however I am encountering errors when trying to display the gauge chart. https://i.sstatic.net/00fby.jpg I hav ...

How to conditionally disable the <a> tag in Angular

I'm facing a challenge with disabling a link within an Angular template. Is it even possible to achieve this? Here is what I have so far: <a [routerLink]="['/details', item.id]" [disable]="disable"> <div clas ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

Disguising the Navigation Bar when choosing from various databases

I am currently facing the following issue: <div class="container"> <h3 class="d-flex justify-content-center">Database</h3> <div class="row"> <div class="col-xs-12"> < ...

Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to retu ...

Tips for troubleshooting Angular 4 unit testing using jasmine and karma with simulated HTTP post requests

I have a service that I need to unit test in Angular 4 using TypeScript and Jasmine. The problem is with the http where it needs to perform a post request and get an identity in return, but for some reason, no data is being sent through. My goal is to ac ...

In Javascript, determine the root cause of a boolean expression failing by logging the culprit

Within my JavaScript code, I have a complex predicate that comprises of multiple tests chained together against a value. I am looking for a way to log the specific location in the expression where it fails, if it does fail. Similar to how testing librarie ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

Error message: VSCode is reporting an issue with TSLint, stating that the current working

I'm currently working in VSCode using TSLint version 5.11.0. In my VSCode settings, I have enabled the following option: "tslint.autoFixOnSave": true However, every time I open a TypeScript file, I encounter the following TS error message: [Info - ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

Guide to integrating ua-parser-js with angular 4

Is there a way to retrieve the OS name, OS version, browser name, browser version, and device from the user agent using User Agent Parser JS in Angular 4? I attempted using [email protected], but it did not provide me with the OS version and device ...

Tips on updating TypeScript to a higher major version

Despite upgrading all packages, deleting node_modules and package-lock.json, and reinstalling with npm install, the typescript runtime in my git repo is still showing version 4.9.5. How can I update the tsc version to be higher than 5.0? $ npx tsc --versi ...

The output indicated an error: Unrecognized argument: '--extract-css'

Encountering the error "The NPM script 'start' exited without indicating that the Angular CLI was listening for requests. The error output displayed an unknown option: '--extract-css'" I recently revisited a project that had been untou ...

Adjusting Mat Expansion Indicator Rotation

After successfully moving the mat Indicator to the left and using the transform attribute to make it turn inward when expanding, I now want to style it so that the indicator faces upward when expanded and downward when collapsed. How can I achieve this uni ...

Using Typescript to set a custom timeout duration based on a dynamic variable within a for loop

My function includes a timeout that changes every 3 seconds: setActiveImage(promotions) { for (let i = 0; i <= promotions.length - 1; i++) { setTimeout(()=> { this.activeImage = 'http://myrul/public/Commercials/' + promo ...

What is the process for ensuring that an object's property values must include specific substrings?

Exploring possibilities for an API configuration system and seeking guidance on typing a config object. Clarification: This pertains to a resources/endpoints configuration for the API, where each resource/endpoint has a defined path containing specific pa ...

Unable to execute the "install code command in PATH" command

I am encountering an issue with Visual Studio Code where the "install code command in path" option does not show up when I try to access it using Shift + Ctrl + P. My operating system is Windows 10 and I am running the latest version of Visual Studio Code. ...