"Is there a way to dynamically remap an array only when there are changes

One of the challenges I am facing is with a component called Page, which contains two components - Editor and Preview.

Page has an array called items.

[
    {
        value: 0,
        text: 'Item 1'
    },
    ...
]

This array items is passed to both Editor and Preview like so:

<editor  [items]="items"></editor>
<preview [items]="items"></preview>

The Editor component has the functionality to add, delete, edit, and reorder items.

The issue arises when Preview requires this array in a different format.

[
    {
        index: 0,
        label: 'Item 1'
    },
    ...
]

I tried creating a function to remap the items into radioItems:

getRadioItems(): any[] {
    const items = [];
    for (let i = 0; i < this.items.length; i++) {
        items.push({ index: this.items[i].value,
                     label: this.items[i].text });
    }
    return items;
}

And then using it like this:

<radio-list [radioItems]="getRadioItems()"></radio-list>

However, this causes the radio list to refresh hundreds of times per second, making it impossible to change values without them being reset upon each refresh.

If there was no need for remapping, everything would work fine. What is the correct way to remap items to radioItems in this scenario?

Answer №1

One potential solution could be to experiment with adjusting the ChangeDetectionStrategy setting of your preview component to OnPush. This change may limit change detection only when there are updates to the @Input() items.

Answer №2

Although unconventional, this solution is effective.

getRadioItems(): any[] {
    const newJson = JSON.stringify(this.items);
    if (this.json === newJson) {
        return this.cachedItems;
    }

    this.json = newJson;
    this.cachedItems = [];
    for (let i = 0; i < this.items.length; i++) {
        this.cachedItems.push({ index: this.items[i].value,
                                label: this.items[i].text });
    }
    return this.cachedItems;
}

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

Having trouble with Ionic 4 navigation not triggering after a single click, requiring multiple clicks to navigate

I have a long list of items, around 40 in total, that load a page describing each item with photos, URLs, and other content. However, I find that I need to click two to three times before reaching this page. I suspect that the excessive use of HTML compone ...

Updating tooltip text for checkbox dynamically in Angular 6

Can anyone help me with this code? I am trying to display different text in a tooltip based on whether a checkbox is active or not. For example, I want it to show "active" when the checkbox is active and "disactive" when it's inactive. Any suggestions ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

JavaScript comparing elements within an array

I need help extracting all the names from an array with URLs containing '/blekinge' and presenting them in a list. Here's what I have so far: const allLocations = locations.map((location) => <li>{location.url}</li> ) I&a ...

Clearing transformation offset in Angular Material Drag and Drop

In my web application, I am working with a <div> element that has the CSS property position: absolute, placed inside a container with position: relative. The left and top properties of this element are linked to data X and Y in the backend component. ...

Click the button to send the form without including any hidden HTML element array value

My main goal is to create a dynamic dropdown menu for users when they click a button. Each click triggers a new dropdown to appear. To achieve this, I have been cloning a hidden div each time the button is clicked. Here's an example of how I am accom ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Tips for troubleshooting a Typescript application built with Angular 2

What is the best approach for debugging an Angular 2 Typescript application using Visual Studio Code or other developer tools? ...

What is the best way to send multiple responses from an Express server using res.write and execute a specific action after each write operation?

I currently have an active express server that is sending data using res.write() Fetcher.js function fetcher() { console.log("fetcher function called") fetch('/units.html', { method: "POST", body: JSO ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

What is the reason behind only the final input value being shown on the screen?

I'm encountering an issue with my input fields. I have a total of five input fields. After filling all of them and clicking the button to display them on the screen, only the last one I entered is shown in all places... (let me know if this explanatio ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

An effective way to pass an array as data to an express router from Angular

I've been attempting to retrieve more detailed information for multiple ID's from the database, but I've hit a roadblock. Below is the array of member ID's: var memberIds = ["2892056", "2894544", "2894545" ...

Struggling to retrieve variable within the .catch function in Ionic 3

I am having trouble accessing the toast variable from the constructor in order to toast errors. It keeps showing as undefined, and I'm not sure why. This issue seems to only occur in this class, which is strange. The error message reads "ERROR TypeErr ...

At what point is a service generated through dependency injection?

Within my Angular service, there is some initialization code within its constructor. I am curious to know when this code gets executed - is it when the service is first provided in a module, or does it wait until the first component injects it? Does th ...

Troubleshooting compilation issues when using RxJS with TypeScript

Having trouble resolving tsc errors in the code snippet below. This code is using rxjs 5.0.3 with tsc 2.1.5 import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import 'rxjs/Rx'; let subject ...

Creating detailed documentation comments for TypeScript within Visual Studio

When using C# with ReSharper and StyleCop, I am able to automatically generate basic documentation comments for methods. This includes sections such as: /// <summary> /// The login. /// </summary> /// <param name="returnUrl" ...

What is the best way to retrieve a specific field from the observable data stream?

When working with observables, I often find myself using them like this: ... const id = 1337; this.service.getThing(id).subscribe( suc => doSomething(suc.name), err = doSomethingElse() ); Lately, I've been utilizing the async pipe more freque ...

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

What is the best way to utilize RxJS for grouping data results, ordering them, and selecting specific items, while also retrieving data from the RxJS

Could you assist me in creating a query that groups by smileTypeId and counts rows by id, then orders by count in descending order and takes the top 2? Retrieve the Smiles array from the RxJS store. View Screenshot Get Post Smiles posts = [ { &quo ...