Transferring Arrays in Angular: A Step-by-Step Guide

I am trying to assign one array to another

        orders = [
           {
            'id': PROCESSING,
            'displayName': 'Processing'
           },
           {
            'id': SHIPPED,
            'displayName': 'Shipped'
           }
        ];

        cloneOrders = [];

setOrders() {
        this.orders.forEach((order: any) => {
                this.cloneOrders = order;
        });
    }

However, when I attempt to access the values of 'cloneOrders' in another function, it returns an empty array

getOrders(status, minutes) {
        this.cloneOrders .forEach((order: any) => {
                console.log(order);
        });
    }

Both functions exist in the same component. Can someone please assist me with resolving this issue? Thank you.

Answer №1

Check out this example

updateOrders() {
        this.newOrders = [...this.orders];
    }

Keep up the good work and happy coding!

Answer №2

In order to populate an array, it is necessary to utilize the .push method.

this.orders.forEach((order: any) => {
       this.cloneOrders.push(order);
 });

An alternative approach using ES6 and the spread operator can simplify the process:

setOrders() {
        this.cloneOrders= [...this.orders];
}

Answer №3

For those in need of deep cloning -

let clonedItems = this.cloneOrders.map(item => Object.assign({}, item));

Answer №4

Instead of assigning a new object from orders to cloneOrders every time, make sure to push the orders in cloneOrders using the following function:

updateOrdersList() {
        this.orders.forEach((order: any) => {
                this.cloneOrders.push(order);
        });
    }

Answer №5

One way to accomplish this is by utilizing the spread operator in ES6.

items = [
 {'id': PENDING,'displayName': 'Pending'},
 {'id': COMPLETED,'displayName': 'Completed'}
];

copiedItems = [];

copyItems(){
  this.copiedItems= [...this.items];
}

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

Passing data and events between components in React

I'm currently working on developing a dashboard app that includes a basic AppBar and a drawer. I based my design on this Demo. https://codesandbox.io/s/nj3u0q?file=/demo.tsx In the Demo, the AppBar, Drawer, and Main content are all contained within ...

Alter the class based on the incoming string from the rxjs stream

I have a stream that outputs strings, and based on these strings I want to apply certain classes to a specific tag: If the string is "ok", add class "fa-check" If the string is "loading", add classes "fa-spin" and "fa-spinner" If the string is "error", a ...

Eliminate any injections from the constructor with the message: "Kindly include a @Pipe/@Directive/@Component annotation."

I've searched through all the questions here, but nothing seems to solve my issue :( I'm working with a hybrid app "@angular/common": "4.4.6", "@angular/compiler": "4.4.6", "@angular/core": "4.4.6", "@angular/router": "4.4.6", "@angular/upgrade ...

Issue with Angular 2 directive update detection; unresolved directive not refreshing

I have created an Angular 2 application that displays a number which can be either negative or positive. In order to change the font color to red when the value is negative, I've implemented a directive. This number gets updated constantly through an ...

Angular application experiencing issues with loading React web component: encountering error when attempting to search for 'adoptedCallback' using 'in' operator with undefined value

I recently created a basic web component using React import React from "react"; import ReactDOM from "react-dom/client"; import reactToWebComponent from 'react-to-webcomponent'; function Test() { return ( <h1> He ...

Determine whether a many-to-many relationship involves a specific entity

I am currently working on developing an API for managing surveys. One challenge I'm facing is determining whether a specific user has moderation privileges for a particular survey. A many-to-many relationship has been set up between the two entities. ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

Typescript raises a error notification regarding the absence of a semicolon when importing a JSON module

Attempting to import a local JSON object into my Vuex store using const tree = import('@/articles/tree.json');. The setting "resolveJsonModule": true, has been enabled in my tsconfig.json and it loads successfully, however NPM is flooding the out ...

Having trouble with routerLink in your custom library while using Angular 4?

In my Angular 4 project, I have developed a custom sidebar library and integrated it into the main project. My current issue is that I want to provide the option for users to "open in new tab/window" from the browser's context menu without having the ...

Angular input field displaying X

Hey everyone, I'm currently working with Angular and typescript. I have a requirement to hide the first 8 characters that the user enters and only show the remaining 4 characters. Update: I have included a link to the Stackblitz demo Stackblitz <i ...

Using callback functions with server.listen in Typescript and JavaScript

I'm puzzled why the following codes are not functioning in TypeScript. (They used to work perfectly fine in my previous JavaScript code!) http.createServer(app).listen(port, (err) => { # Do something }); However, this code works flawlessly (wi ...

How can I center align my loader inside app-root in Angular2+?

I've successfully added a basic spinner to my <app-root> in the index.html file. This gives the appearance that something is happening behind the scenes while waiting for my app to fully load, rather than showing a blank white page. However, I& ...

Modify interface property type based on another property

Currently, I am tackling a grid project in React and have come across specific types and interfaces (view code here): export type DataGridColumnType = 'currency' | 'date' | 'number' | 'text'; interface CurrencyColum ...

Modifying the Dropdown height in Angular: A step-by-step guide

Currently, I am utilizing Angular, Angular Material, and css I'm facing difficulties in reducing the height of the mat-select Dropdown and achieving proper vertical alignment for the text inside it. <mat-select class="frequency-dimensions&quo ...

Ways to showcase information based on the chosen option?

Is there a way to display data based on the selected value in a more efficient manner? Currently, when clicking on a value from the list on the left side, new data is added next to the existing data. However, I would like the new data to replace the existi ...

Preventing RXJS SwitchMap from repeating a request once it has been terminated

switchMap does not repeat HTTP calls. I have developed a directive that validates email existence. Within the directive, there is an API call triggered on each keypress to check for email existence. To prevent multiple HTTP requests and cancel previous ...

Unable to inject service into Angular UseFactory Provider

After creating a generated API Client with Nswag and ASP Net Core, I needed to set the base URL for the client using the following code: export const BASE_API_URL = new InjectionToken<string>( "BASE_API_URL" ); @Injectable({ providedIn ...

Ways to pass a class list from a client to a webmethod using AJAX

I have a list of client-side classes in TypeScript that I need to send to a web method. Here is my TypeScript code: class MakeReportData { LocalName: string; FldSi: number; ViewSi:number; TypeName:string ; CheckBoxshow :boolean ; ...

Is there a way to access the element reference of a component directly within the template?

When I mouse over certain elements, I use the following code to set focus: <div #divTemplateVar (mouseover)="divTemplateVar.focus()"></div> However, this method does not work for components: <component #componentTemplateVar (mouseover)="c ...

How can we dynamically replace diagram.model in GoJS?

Is there a way to update the GoJS diagram on my webpage dynamically when new JSON data is fetched from a service? I tried triggering this change with an event like clicking a button, but I keep running into errors indicating that the div already has a di ...