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>