Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly.

The issue arises when clicking on the favorite button causes all project cards to reset and the favorite icon remains unchanged. Below is a snippet of code for reference:

project-carousel.component.html

<app-project-card *ngFor="let project of projects" [project]="project" [isFavorite]="isFavorite(project.id)"></app-project-card>

project-card.component.html

<div class="project-fav-btn" (click)="favorite()">
     <i [ngClass]="{'fas':isFavorite, 'far':!isFavorite}" class="fa-heart"></i>
</div>

project-card.component.ts

export class ProjectCardComponent implements OnInit {

  @Input() project: Proje;
  @Input() isFavorite: boolean;

  constructor(private favoriteService: FavoriteService) {
  }

  ngOnInit(): void {
  }
  
  favorite(): void {
    if (this.isFavorite) {
      this.favoriteService.deleteFavorite(this.project.id);
    } else {
      this.favoriteService.addFavorite(this.project.id);
    }
    this.isFavorite = !this.isFavorite;
  }
}

If you have any suggestions on how to address this issue or approach it differently, please share them.

Answer №1

If you're experiencing issues, try incorporating the trackBy function with your ngfor loop. This method is likely to resolve the problems you are encountering.

To learn more about implementation, refer to the Angular documentation here.

You can also consider utilizing the following code snippet:

<app-project-card *ngFor="let project of projects; trackBy:trackByProjectId" [project]="project" [isFavorite]="isFavorite(project.id)" ></app-project-card>

In your component.ts file, include:

trackByProjectId(index: number, project: any): string {  
    return project.id;  // Ensure a unique key is returned from your project data 
  }  

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

Encountering the error message "Unable to access property 'addEventListener' of null while trying to manipulate innerHTML"

Currently, I am utilizing innerHTML to include certain elements and a wrapper around them. for (i = 0; i < arr.length; i++) { b.innerHTML += "<div class='wrapper'><div class='col-4'>" + arr[i].storeID + "</div> ...

The radial gradient in d3.js does not properly affect paths

My goal is to create a radial gradient on my path element, but for some reason the radial gradient does not apply correctly. Can anyone help me troubleshoot this issue? Below is my updated code: // Define the canvas / graph dimensions var margin = {top: ...

Visual Studio Code encounters a Node.js error stating "Module not found"

I have been struggling to run my Node.js program in VSCode. Despite trying various solutions found on StackOverflow, none of them seem to be working for me. I even attempted the Json file method, but unfortunately, that didn't work either. internal/mo ...

Combining Angular subscriptions to fetch multiple data streams

I am looking to retrieve the most recent subscription from a group of subscriptions. Whenever the value of my FormControl changes, I want to capture only the latest value after the user has finished typing. Below is the code snippet I am using - let cont ...

Can you recommend a basic, invertible, non-secure string cipher function that performs exceptionally well in terms of data dispersal?

I am in need of creating two functions to obscure and reveal a string, following the structure below: string encrypt(string originalText, string key) string decrypt(string scrambledText, string key) I require these functions to be concise and easy t ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

Adding Bootstrap modal content to a webpage before it renders is a simple process that involves preloading the

When using Bootstrap modal, is it possible to load a remote URL along with the parent page without needing to click on a button? ...

Pinterest's "Pin it" button causing issues with the 'back' function in Internet Explorer

Recently, I discovered a problem with the "Pin it" button for Pinterest in Internet Explorer (v9 at least). It seems that this button is causing issues with the 'back' functionality in the browser. When right-clicking on it, an entry like '& ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

What is the best way to update the mat-tab when the routeParameters are modified?

I need to reinitialize the mat-tab-group in order to make the first tab active when there is a change in the routeParams. ts file: public index = 0; ngOnInit() { this.subscription = this.route.params.subscribe((routeParams: Params) => { // some ...

Retrieving data from a child component that has been added in React

One of the challenges I am facing is dealing with a main react component that dynamically appends child components, like <Child />, on button click The structure of my Child component looks something like this: <form> <input .... /> ...

.npmignore failing to exclude certain files from npm package

I'm facing an issue with a private module on Github that I am adding to my project using npm. Despite having a .npmignore file in the module, the files specified are not being ignored when I install or update it. Here is what my project's packag ...

Is there a way to effectively alter an object that has been assigned in a separate file?

Seeking Assistance: I am facing an issue in my current project where I need to store a javascript object in an external file and then export it using module.exports. The challenge now is that I want another file to be able to modify a specific value withi ...

The submit button is unable to initiate the ajax function

I encountered an issue with my code while attempting to separate my form function into a different PHP file and utilize an Ajax function to call the form based on the IDs. However, after separating the form function, the submit button no longer triggers th ...

When hovering, apply style 1 to all elements with the same id, and style 2 to the hovered element

I'm working with some user-generated divs that I want to dynamically highlight when hovered over, while simultaneously blurring the other divs. My challenge is figuring out how to change the style of the hovered div separately from all the others. Th ...

Troubleshooting Problems with Owl Carousel Loading

Having trouble with Owl Carousel loading issue. I've set up my carousel using the Owl Carousel jQuery plugin as guided, but it's showing me an "owl-carousel loading" class added to the DOM (owl-loading). I've tried adding custom styles and J ...

Transferring a single dataset from a table to a pop-up modal using Angular

I am working on a table to display entries for a contest, extracted from a database using PHP and converted into a .json object for AngularJS and JavaScript. I want to add a modal feature so that when a "judge" clicks on an entry, they can view its details ...

Guide to uploading multiple images to an Amazon AWS S3 bucket using Node.js, Angular, and JavaScript

Can anyone share insights on where and how E-commerce websites typically upload their product images? Has anyone had experience using Amazon AWS S3 bucket for this purpose? Additionally, does anyone know how to upload or retrieve multiple images at once ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...

Having trouble with the Slide Toggle menu closing unexpectedly?

$('span.nav-btn').click(function () { $('ul#menu').slideToggle(); }) $(window).resize(function () { if ( $(window).width() > 900) { $('ul#menu').removeAttr('style') } }); $('spa ...