Preventing dynamically generated components from reinitializing upon adding a new object

Within my application, there is a unique feature where components are dynamically generated through a *ngFor loop. Here is an example of how it is implemented:

<div *ngFor="let actionCategory of actionCategories | keyvalue">
    <h2>{{actionCategory.key}}</h2>
    <div *ngFor="let action of actionCategory.value | keyvalue">
        <app-gearset [action]="action"></app-gearset>
    </div>
    <button mat-button (click)="addComponent(actionCategory)">Add another set</button>
</div>

Users can further enhance their experience by adding more components through the button connected to the addComponent() function. Take a look at the function below:

  addGearSetComponent(actionCategory) {
    this.actionCategories[actionCategory.key][Object.keys(this.actionCategories[actionCategory.key]).length] = {};
  }

Upon invoking this function, a new empty object is appended to the designated actionCategory object, resulting in the addition of a new component to the relevant section of the application. However, the challenge arises when the existing components lose their state each time a new one is added.

Is there a way to preserve the state of the existing components within the object, despite modifications made to the object they are associated with? Alternatively, is there a more effective approach to dynamically creating components based on a sophisticated object structure?

Answer №1

After spending more time digging through documentation, I stumbled upon the trackBy feature. [trackBy][1]

It seems that by providing trackBy with the following function, I can manipulate how components are re-rendered in the DOM:

trackAction(index, action) {
    return action ? action.key : undefined;
}

I must confess, I don't completely grasp the inner workings of this, but it effectively stops existing components on the page from being destroyed and re-rendered when a new one is added. I'll need to monitor for any potential performance issues, but I believe this solution will suffice for now! :) [1]:

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 a 500 internal server error while accessing the web server

Anyone out there able to assist? My web service seems to be throwing an error. Receiving a 500 Internal Server Error and 304 Not Modified message The requested XML data is not displaying the body content as expected. var soapMessage ='<soap:E ...

What is the best way to declare module variables in a Node.js environment?

When it comes to declaring variables when requiring modules in nodejs, there are different styles followed by well-known developers. For instance, TJ Holowaychuk uses a style like this: (method1) var connect = require('connect') , Router = req ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...

Stop working to $(this) in jquery when clicking outside

I'm facing an issue with my code and would like some help. I have a button that toggles the visibility of a filter element, which is working fine. However, I now want to implement a "click outside" effect to close the filter when clicking on any body ...

Go back to the previous selection in the Select field if the JavaScript Confirm function returns a false value

I am dealing with an HTML select field that has one option pre-selected. Whenever another option is selected, a change event is triggered which displays a confirmation prompt. What I am trying to achieve is, if the user cancels the confirmation (i.e., if ...

What is the best way to generate a random string output from an object in JavaScript?

I'm struggling with extracting a random value from the object provided below, can anyone help me out? const hellos = { English: "Hello", Japanese: "Konnichiwa", German: "Hallo", Spanish: "Hola", Arabic: "Ah ...

Is there a way to effortlessly launch a new window with just a single click?

I'm encountering an issue with a function that is supposed to open a new window when a button is clicked. Strangely, on the first click, nothing happens, but on the second click, the window finally opens. Here's my code: Script <script src ...

Error: TweenLite has not been recognized

/justincavery/pen/mPJadb - this is a link to CodePen After copying the code from CodePen and running it, I encountered an error: "Uncaught ReferenceError: TweenLite is not defined". The image only draws once and there is no animation unless I press "F5 ...

A guide to displaying JSON data with Ajax

I am diving into the world of Ajax and feeling a bit puzzled about extracting all values from a specific source. <html> <head> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></sc ...

What is the best way to execute the angular-phonecat tutorial tests while the server is operating without a graphical user interface?

The angular-phonecat demo assumes that your server has chrome installed and you are running it there. When you run the command npm test, the local chrome browser should launch and continuously run the tests. However, if you are using a headless server li ...

Guide on how to align the bootstrap popover's arrow tip with a text field using CSS and jQuery

I have tried multiple solutions from various questions on Stack Overflow, but I am still struggling to position the arrow tip of the bootstrap popover correctly. html: <input type = "text" id="account_create"/> js: $('.popov ...

In my attempts to retrieve specific statistics from the PokeAPI using Axios and Node.js, I encountered an error

Having an issue while trying to utilize the Pokemon API. Whenever attempting to access the attack, HP and speed stats, all Pokemons show up as undefined! Can someone please point out what might be wrong with my API call? const axios = require('axios&a ...

Determining with jQuery if the right element has been successfully "dropped"

Imagine having 10 different draggable boxes and 2 droppable areas. You need to correctly match 5 boxes with droppable area 1 and the other 5 with droppable area 2. If a box intended for droppable area 1 is mistakenly dropped into area 2, it should not wor ...

Encountering the error message: "Unable to access the 'valid' property of an undefined object in Angular 5 template form"

I want to build a Model-Driven Angular template for registering new users. I've set up two main files for this: admin-register.component.html admin-register-form.component.ts However, when I try to access the page with the registration form, I encou ...

Combining disparate arrays with serialized name/value pairs

Is there a way to merge an unassociated array with serialized name/value pairs without manually iterating over them? //First, I select certain values from mytable var data = $('#mytable input:checked'); console.log(data); //Object[input attribu ...

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...

Creating a custom data type using values from a plain object: A step-by-step guide

I recently came across an object that looks like this: const myObject = { 0: 'FIRST', 10: 'SECOND', 20: 'THIRD', } My goal is to define a type using the values from this object, similar to this: type AwesomeType = &apos ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

The jQuery click function triggers immediately upon the loading of the page

Despite my best efforts to resolve this issue independently and conduct extensive research on Google, I am still unable to identify the root of the problem. It seems that the click function continues to activate upon page load. Kindly elucidate the under ...

How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this: { "network": [ { "name": [ "John", "Jill", "June" ] }, { "town": [ "London", "Paris", "Tokyo" ] }, { "age" : [ "35", "24", "14" ] } ] } Unfortunately, my data is in this format and I have to work w ...