How can I change the state of a button that is inside * NgFor when consuming an API? The issue arises when I try to toggle the favorite status from one to another, as it changes all buttons instead of just the one clicked. Is there a way to maintain the state of each button individually?
Service
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class ServiceService {
constructor(private http: HttpClient) { }
private url = 'https://rickandmortyapi.com/api/';
getAllApi(){
return this.http.get(`${this.url}/character`)
}
pagination(pagination:number){
return this.http.get(`${this.url}/character/?page=${pagination}`)
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/services/service.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
Characters: any[] = []
NewCharacters: any[] = []
public page = 1;
public status = false;
constructor(private apiService: ServiceService) {
this.getAllCharacters()
}
ngOnInit(): void {
}
getAllCharacters() {
this.apiService.getAllApi()
.subscribe((data: any) => {
this.Characters = data.results;
console.log(data)
})
}
getNextCharacters(pagination: number) {
this.page = this.page + 1;
console.log(this.page)
this.apiService.pagination(this.page)
.subscribe((data: any) => {
this.NewCharacters = data.results
console.log(data)
})
}
updateFavoriteStatus(status:boolean){
this.status = status
}
}
html
<div class="container mt-5">
<button (click)="getNextCharacters(1)" class="btn btn-outline-dark m-2">Next</button>
<div class="card-columns" *ngIf="page < 2; else elseBlock">
<div class="card text-center" *ngFor="let character of Characters">
<img class="card-img-top" [src]="character.image" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{character.name}}</h5>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional
content. This content is a little bit longer.</p>
</div>
<button (click)="updateFavoriteStatus(false)" *ngIf="status; else elseFav" class="btn btn-success btn-block"><i class="far fa-star"></i> Favorite</button>
<ng-template #elseFav>
<button (click)="updateFavoriteStatus(true)" class="btn btn-outline-success btn-block"><i class="fas fa-star"></i> Favorite</button>
</ng-template>
</div>
</div>
<ng-template #elseBlock>
<div class="card-columns">
<div class="card text-center" *ngFor="let newCharacter of NewCharacters">
<img class="card-img-top" [src]="newCharacter.image" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{newCharacter.name}}</h5>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to
additional
content. This content is a little bit longer.</p>
</div>
</div>
</div>
</ng-template>
</div>
Appreciate any assistance provided.