"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

What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, espe ...

Guide to implementing validation in an angular 2 dropdown using the Model-driven Approach

When the user clicks the submit button, the dropdown validation does not occur. I want the form to be validated if the user does not select any value, and in that case, the form state should be invalid. In my scenario, I have disabled the submit button whe ...

Discovering the power of angular async binding in your projects can greatly

Is there a way to achieve something similar to <span *ngIf="admins.includes(name) | async"> where the admins is declared as Observable<string[]> in the component class? I understand that this code may not work, but is there a workaround to make ...

PHP code to store the start and end dates of a week in an array

Can someone help me with PHP code to format the start and end date of a week like this? Range: 16-Jan-2018 to 22-Jan-2018 I have the start and end dates, but I'm struggling to store them in an array for multiple weeks under one index. For example: ...

Revamping every Angular component

Looking for a shortcut to upgrade all my Angular components at once. When checking my Angular version with ng v globally in VS Code terminal, results differ between overall and project directory settings: https://i.stack.imgur.com/2iOJx.png https://i.st ...

Using JavaScript to organize and reformat JSON data into grouped structures

In my dataset, I am unable to make any formatting adjustments or modifications. //input json data [ { "Breaks":[ {"points":12,"points_total":12,"average":8.0,"faults":[]}, {"points":17,"points_total":29,"average ...

What is the best way to manage destroyed objects?

I've been working on a PIXI.js application and I'm faced with the challenge of managing resources to prevent memory leaks. To address this issue, I am utilizing the DisplayObject.destroy method. When a display object is destroyed, many of its in ...

The issue arises when trying to pass multiple parameters with the Angular 2 router and encountering

After creating a sample Plunker to pass multiple parameters to the next page, I encountered an issue where the crisis center routing failed to work properly upon clicking on items. See the demonstration on Plunker here: http://plnkr.co/edit/ngNSsKBzAuhaP0E ...

Tips on updating checkbox background color after being selected

I've been working on creating checkboxes for seat selection in Angular using a TypeScript file, but I'm facing an issue where the background color of the checkbox doesn't change after checking them. Here's my TypeScript function: gener ...

When using react-admin with TypeScript, it is not possible to treat a namespace as a type

Encountering issues while adding files from the react-admin example demo, facing some errors: 'Cannot use namespace 'FilterProps' as a type.' Snippet of code: https://github.com/marmelab/react-admin/blob/master/examples/demo/src/orde ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

After updating from angular4 to angular 5, the npm test is failing with the error message "TypeScript compilation cannot find test.ts file"

After upgrading my app from Angular4 to Angular 5 using the steps provided on https://update.angular.io/, I encountered an issue. While I can successfully run ng-serve and ng build without any problems, the npm test command for ng test is failing with the ...

Can a custom CSS be linked directly to the angular-cli.json file?

I'm trying to incorporate custom CSS into my angular-cli.json file, but I haven't been able to find a successful method. I attempted to use the following code: "styles": [ "styles.css", "http://site.test/mycss.css" ], However, it does ...

How to modify the background color within the mat-menu-panel

Incorporating angular 9 and less into my current project, I have encountered an issue with a mat-menu-panel where my mat-menu-item is located. While I have successfully changed the color of my mat-menu-item, I am now faced with the challenge of changing th ...

Insufficient attributes in TypeScript component for React application

Developing with React import {Input} from '@xxx/forms'; <Input label="account Name" name="account"/> Type Definition for input import React, { Ref } from 'react'; import { InputProps as UITKInputProps } from ...

How can an Angular 2 component detect a change in the URL?

My Angular 2 component subscribes to a service based on the URL hash without calling any subcomponents. I am wondering if I should use Route or Location for this scenario, and how can I listen for and react to a pop state event? ...

Mongoose does not compare BCRYPT passwords that are empty

I'm currently working on incorporating bcrypt into my mongoose model using typescript. Referencing this link as a guide. However, since my project is in typescript, I'm unable to directly use the provided code. I'm confused about how they&a ...

Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. ...

What are the benefits of sharing source files for TypeScript node modules?

Why do some TypeScript node modules, like those in the loopback-next/packages repository, include their source files along with the module? Is there a specific purpose for this practice or is it simply adding unnecessary bulk to the module's size? ...

Encountering an "Invalid hook call error" while utilizing my custom library with styled-components

I recently developed my own custom UI tool using the styled-components library, integrating typescript and rollup for efficiency. One of the components I created looks like this: import styled from 'styled-components' export const MyUITest2 = s ...