How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt:

Typescript

import { Component, Input, NgZone, OnInit } from '@angular/core';
...

@Component({
    selector: '...',
    templateUrl: '...'
})
export class MyComponent implements OnInit {
    ...
    staticKpi = [];
    
    constructor(...) {
        super();
    }

    ngOnInit(): void {
        this.initializeComponent();
    }

    private initializeComponent() {            
        let row = []; // For example, Apple, Banana, Mango, etc
        ...
        // GET CALL TO AN API TO POPULATE row[]
        ...
        this.staticKpi.push(row); // <--- THIS I WANT TO CLEAR AFTERWARDS
        row=[]; // CLEAR THE ARRAY
    }
}

HTML/Template

<div *ngFor="let element of staticKpi">
    <h2>element</h2>
</div>

Once staticKpi has been rendered, I aim to reset the array so it is primed for the next GET call, as opposed to accumulating additional elements on top of the existing ones. However, currently, nothing is being displayed. I suspect that the array may be getting cleared immediately after being populated. Can you identify where I might be going wrong?

Answer №1

*ngFor="let item of dynamicKpi"

cycles through dynamicKpi and renders the content for each item contained within that array;

Only the items present in the array at the current moment will be displayed, so if you want to preserve them, it's necessary to save the data in a different array after each iteration and loop over that array in the template;

Answer №2

When working with JavaScript, it's important to remember that Arrays and Objects store references. This means that if you pass an array between functions and one function modifies the array, all other references to that array will be affected. To avoid this issue, you should create a new array instead.

Instead of:

this.staticKpi.push(row);

You should use:

this.staticKpi.push([...row]); // This creates a new array

Now, even if you do:

row = []

The copy of the array stored in staticKpi will remain unchanged.

Answer №3

If my understanding is correct, you intend for the array named staticKpi to be empty every time the method initializeComponent is called.

import { Component, Input, NgZone, OnInit } from '@angular/core';
...

@Component({
    selector: '...',
    templateUrl: '...'
})
export class MyComponent implements OnInit {

    staticKpi = [];
    
    constructor() {
         //super(); // It's unnecessary to do this as this component doesn't extend another component. 
    }

    ngOnInit(): void {
        this.initializeComponent();
    }

    private initializeComponent() {  
        // Start by clearing the array
        this.staticKpi = [];  
         
        // Whenever the initializeComponent method is called, @var row will always be an empty array
        let row = []; // For example: Apple, Banana, Mango, etc
        // Merge the arrays together or simply assign row to staticKpi
        this.staticKpi = [...this.staticKpi,...row];

    }
}

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 best method to incorporate filtering in a CRUD table?

Frontend code: // Importing necessary components and libraries import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; import { Chart, Tooltip, CategoryScal ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

Setting up Node on a Ubuntu system

Currently, I am in the process of installing Node.js to run my Angular2 program. However, I encountered an error during the installation: npm WARN npm npm does not support Node.js v0.10.25 npm WARN npm You should probably upgrade to a newer version of nod ...

Husky 5: The Ultimate Gitignore Manager

Last week, a new version of Husky was released, known as Husky 5. I came across an interesting article discussing the features and updates in this release that can be found here. Upon migrating to Husky 5 (), I discovered a new directory named .husky with ...

Guide on adjusting the scroll position in tinyscrollbar on page load

I have integrated tinyscrollbar into my project. One of the options available is contentPosition (Number, indicating the position of the content relative). Yet, I am struggling to modify it as needed. This is how my current JavaScript code looks: $(do ...

Shared Vue configuration settings carrying over to Jest spec files

For my unit testing of components using VueJS and Jest, I'm incorporating the Bootstrap Vue library for styling. To address console warnings regarding unknown plugins, I've set up a configuration file: import { createLocalVue } from '@vue/t ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

Obtain a URL using JavaScript's regular expressions

Is it possible to use JavaScript regex to fetch the first function parameter? For instance, when I click on a tag in this page element, how can I extract the inline link? Here's an example: <li><a href="#blog" data-rel="clos ...

Issue: [ng:areq] The parameter 'PieController' is not properly defined, it is currently undefined

Why am I getting an error when using ng-controller='DoughnutCtrl' in a dive? Error: [ng:areq] Argument 'DoughnutCtrl' is not a function, got undefined Here is my Chart.js code: 'use strict'; angular.module('portfoli ...

strange issue encountered while utilizing JavaScript's async/await syntax

Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend. // Here is the structure of the API response { info: { // details omitted }, results: [ {//random user data} ] } // This snippet ...

Displaying adornments in a vertical arrangement within a TextField using Material UI

Is there a way to display adornments vertically in a Material UI Textfield? I've been trying but it always shows up horizontally. Snippet: <TextField variant="filled" fullWidth multiline rowsMax={7} onFocus={() => h ...

What is the process of triggering an action from within getInitialProps?

I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've fo ...

Formik's setField function is not properly updating the value of an array when using Material UI's autocomplete

When the data is retrieved from the API, it comes in the following format: otherLanguages:[{code:EN,name:"English"},{code:MD,name:"Mandarin"}] I am attempting to initialize the Autocomplete with this data: initialValues: { otherLa ...

Typescript error TS2717: All following property declarations should share the same data type

During development on my local host, the TypeScript build works perfectly fine. However, when transitioning to Docker with a Node image, I encounter a peculiar error during the build process: src/middlewares/auth.ts(16,13): error TS2717: Subsequent propert ...

Enhance user information by adding necessary fields

I often encounter situations where I need to select a specific entry from a set of data in a component, whether through a select box or as part of a table. However, the way I intend to utilize this data typically requires additional fields like the "label ...

Storing checkbox status in Angular 7 with local storage

I am looking for a way to keep checkboxes checked even after the page is refreshed. My current approach involves storing the checked values in local storage, but I am unsure of how to maintain the checkbox status in angular 7 .html <div *ngFor="let i ...

"The JQuery .validate method is not compatible with this property or method" - error message displayed

I seem to be facing a problem that I can't seem to solve. I keep getting an error message that says "Object doesn't support this property or method" while using jquery-1.10.4. The .validate method is not functioning properly for me. Any assistanc ...

Ajax cannot seem to come to a resolution

After completing my learning on Ajax, I decided to work on a simple project - a port scanner. However, I am facing issues with it as it is not working properly. The only message that pops up is 'Scan started' and I can't figure out what the ...