Prevent Component Reloading when Editing State in NGRX Angular

Currently, I am facing an issue with a component in my task list application. The problem lies within an observable array that I iterate through using a wrapper with an async pipe. Additionally, there is a child component known as the "Todo component" which contains an input named "Todo" and an attribute called "showDetails" initialized as false, used for UI toggling. Here is the structure:

<div *ngFor="let todo of todo$">
  <app-todo [todo]="todo"></app-todo>
</div>

Within the todo-component template, there is a button to toggle the Boolean value. There is also a function called "toggle" which dispatches an action to update the ngrx state of the todo. However, upon dispatching the action and having the reducer update the state, the entire component is reloaded. This causes the showDetails attribute to revert back to false even if it was previously set to true.

Below is a snippet of the reducer function responsible for updating the state:

  on(Toggle, (state, action) =>
        state.map(i => (i.id === action.id ? { ...i, todo: !i.todo } : i))
  )
           

For demonstration purposes, here is a StackBlitz example: Demo

I am looking to maintain the value of showDetails even after the state change...

Answer №1

One issue is arising because a trackBy function is not being provided to ngFor. Consequently, whenever the array gets updated, ngFor generates new views and destroys the old ones. To resolve this problem, create a trackByFn so that ngFor can identify which element is being modified.

// app.component.ts
trackById(idx, {id}) {
  return id;
} 
<div *ngFor="let todo of todos$ | async; trackBy: trackById" ...

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

Here is a unique rewrite of the text: "Converting to TypeScript: Add the Node Modules Path to the global paths array in the 'module' module using

Utilizing vue ui, I initiated a vue project with typescript and subsequently integrated electron, iview, and less... After addressing the lexical issues in the *.ts files, running the vue-cli-service serve task in vue ui yielded the following output: Tot ...

What methods can be utilized to efficiently determine if one N-ary tree is a subtree of another, besides simply comparing their pre-order strings?

When faced with a problem of determining if one binary tree is a subtree of another, the usual method involves generating strings by performing pre-order traversals on both trees and then using indexOf to check for the presence of one string in the other. ...

Ways to obtain a tab and designate it as the default in angular when using angular material Tabs

I am facing an issue with accessing tabs within a nested component. The parent component contains the tab feature and to reach the tabs inside the child component, I am using the following code: document.querySelectorAll('.mat-tab-group'); The a ...

Transmitting HTML content to the browser from the client using Node.js

Quoted from: Book - "Getting MEAN with Mongo, Express.." When it comes to responding to requests in your application by sending HTML to the browser, Express simplifies this process compared to native Node.js. With support for various templating e ...

What is the proper method for expanding Material-UI components in React using Typescript?

I am currently working on customizing material-ui components by extending them as my own with unique properties, using reactjs paired with typescript. Here is the snippet of code that I have been experimenting with: import React from 'react'; i ...

The use of the cache-control request header field is prohibited when attempting to sign in with an Angular frontend during the

I recently developed an application using Angular with a Java backend in Spring. However, I'm facing an error when trying to log in and it's related to CORS policy. Whenever I try to login, I receive the following error message: Access to XMLH ...

The Intersection Observer API is caught in a never-ending cycle of rendering

I am experimenting with the intersection observer API in order to selectively display elements in a CSS grid as the user scrolls, but I seem to have run into a problem of encountering an endless rendering loop. Below is the code snippet I am working with. ...

Conditional ng-select dropdown functionality

I am seeking a way to showcase the purchaseOrderStatusName within a NgSelect dropdown. The API offers various status values, including: OPEN, RECEIVED, CANCELLED. TS file: RetrieveAllPurchaseOrders() { this.purchaseOrderService.getAllPurchaseOrders ...

A Vue object with dynamic reactivity that holds an array of objects

I've experimented with various approaches, but so far I've only managed to get this code working: // This works <script setup lang="ts"> import { reactive } from 'vue' import { IPixabayItem } from '../interfaces/IPi ...

Tips for showing various tooltip text when iterating through a list?

I am currently working on a project where I am looping through a list and attempting to assign different tooltip text to various icons. However, I am struggling with the implementation. Here is a snippet of my code: <React.Fragment key={sv.key ...

Ways to transmit information or notifications from a service to a component

Currently, I am utilizing Angular 6 and have the upload file control on three different screens (three various components). Each of these screens calls the same method UploadFile(). The main issue arises when I need to make any changes to this method, as ...

Exploring Typescript: Obtaining the type of a nested optional property within an interface

I am facing an issue with the following code snippet: Property 'id' does not exist on type '{ id: string } | undefined.' as group is optional. Despite that, I need to access the type of id. How can I achieve this? interface list{ grou ...

Steps for subscribing to a component variable in Angular 2

I've set up a header for my server URL in one of the components, and I want to use this header in all components whenever there is a server call. However, I am having trouble subscribing to this header. Can someone please assist me? Interface compone ...

"Exploring AngularFire Database: Simple ways to retrieve the total number of items in a list

I attempted to utilize angularfire2 in order to develop a function that retrieves the total number of entries in a list within a firebase real-time database. For instance: Retrieve the count of users in '/users'. I am not interested in continuou ...

Steer clear of duplicating template literal type entries when dealing with optional routes

My code includes a type called ExtractParams that extracts parameters from a URL string: type ExtractParams<Path extends string> = Path extends `${infer Start}(${infer Rest})` ? ExtractParams<Start> & Partial<ExtractParams<Rest>& ...

Switching to Angular's routing, prioritize removal of the previous component

I'm currently using [routerLink]="['my-route']" in my Angular project. However, I've encountered an issue with the routing system where it renders the new component first and then removes the old one from the DOM. This is caus ...

The "my-app" selector in Angular2 did not find any elements upon initial loading

Has anyone encountered this error upon the initial page load in their Angular2 app? It disappears upon navigating through the app, but sometimes reappears if I refresh with CTRL+F5. The routing structure of my app is as follows: AppComponent.ts LoginCom ...

Angular nested routes allow for creating more complex and dynamic

I'm facing an issue with setting up nested routes in my myfile.routing.module.ts file. Whenever I try to access a specific route, it keeps redirecting me back to the home page. Below is the snippet of my code: routing.module.ts . . . const routes: R ...

Counting string properties from imported JSON in Angular 2 can be achieved by iterating through the

What is the easiest method to count a specific attribute in imported json data? I am attempting to calculate the number of instances where the status is "success". I have experimented with pipes but am uncertain about their usage. myjson: { companyA ...

There was an issue encountered while trying to execute npm install, resulting in the error message: "This is a glitch

I am diving into the world of Angular and Node for the first time. I'm currently attempting to run a project that combines Angular with Neo4j, but encountering some issues along the way. When I initially tried to launch the project as is, after openin ...