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

Unable to modify the bar's color using the .css document

Below is the JavaScript code being used: var marginEducation = {top: 20, right: 30, bottom: 40, left: 300}, widthEducation = 1000, heightEducation = 460; const svgEducation = d3.select("#Education") .append("svg") .attr("w ...

Can [] be considered a valid type in Typescript language?

I've come across this function: function stringToArray(s: string|[]): [] { return typeof s === 'string' ? JSON.parse(s.replace(/'/g, '"')) : s; } This function is functioning as expected without any type warnings. Bu ...

NodeJS API Language Configuration

I'm currently working on integrating the DuckDuckGo Instant Answer Api into my NodeJS application. To do so, I am making a data request from the API using Node Request. var request = require('request'); request('http://api.duckduckgo.c ...

Utilizing NodeJS to Refine JSON Data

I am working with a JSON array that consists of multiple objects. My goal is to retrieve objects that have a specific value, such as returning [ service_wog: { count: 48, popular: false, code: 33, price: 20, id: ...

accessing the angular fullstack default application by authenticating via google oauth2

Currently, I have my angular fullstack application running on localhost:9000. I am trying to implement a feature that allows users to log in by clicking the "Connect with Google+" button on the login page. However, I keep encountering an error 400 with th ...

Tips for assisting flow with managing the initialization of react component state

In my React components, I am initializing state like this: export default class LoginForm extends Component { state = { // (*) flash: { message: null, style: null } // initialiser for flash message: show no ...

Tips for declaring the project npm registry within the package.json configuration file

Currently, I am juggling multiple projects simultaneously and facing the issue of each project having a different node module registry. For instance, project A sources its modules from http://registroy.foo.com, while project B pulls modules from http://re ...

Encountered a timeout error of 2000ms while running tests on an asynchronous function within a service

Here is the service I am working with: class MyService { myFunction(param){ return Observable.create(obs => { callsDBfunc(param, (err, res) => { if(err) obs.error(err); ...

Steps for sending a form with jQuery's submit method1. Start

Below is the jquery code that I have written: $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(e ...

Fill the rows of the <Table> using HTML code

I am encountering an issue with displaying data in a table on a screen: <table id="TransactionTable" class="table table-responsive table-striped"> <thead> <tr> <th></th> <th>Date</ ...

Is there a way to fill select boxes with multiple values?

As I set up a jqGrid, I encountered the challenge of visualizing multiple values in one cell. The data is sourced from a form where users can select multiple options. While I managed to display the select box, I struggled with populating it. My attempts to ...

Is there a method to consistently implement a controller function across all routes within a router file in Express?

I have the following code snippets within an application. I am looking for a way to apply "authController.isLoggedIn" to each instance of "router.get" without having to repeat it multiple times. Initially, I thought using router.use might be the solution ...

Function that contains a JavaScript reference and observation

I'm experiencing issues with the code below and I'm having trouble figuring out what's causing the problem. function some(){ for (var i=0;i<....;i++) { var oneObject; ...some logic where this object is set oneObject.watch(prop ...

How come the data I send gets converted to Undefined when working with Tabulator?

I am currently facing an issue with integrating JSON data as search results into my Tabulator. The goal is to display these search results in their respective columns within the Tabulator. Here is the code snippet I have implemented: <body> <div ...

jquery's each method is not functioning as intended and causing unexpected issues

I'm in the midst of developing a website, and one section requires users to input their details into a form. My goal is as follows: When a user clicks the submit button with any empty fields, I want a span element (initially set to display none in CS ...

Utilize Javascript to generate intricate table headers based on JSON data

I am currently facing a challenge in creating an HTML table header with colspan. I have a JSON object as follows: var metadata = [{ "colIndex": 0, "colType": "String", "colName": "PM" }, { "colIndex": 1, "colType": "String", "colName": "PR ...

"When I use breakpoints and run my application in debugging mode, it performs flawlessly. However, without these tools, it

I have developed an application using the Ionic Framework with Firebase as the backend. When I run the application with breakpoints using the debugger, everything works fine. However, if I run it without the debugger, I notice that values are not being upd ...

Issues arising from utilizing Twitter Bootstrap 3.1.x, the box-sizing property, and Revolution Slider

I'm currently working on a PyroCMS theme that is built with Twitter Bootstrap 3.1.x and includes Revolution Slider. However, I've encountered an issue where the property box-sizing: border-box; creates an unwanted grey border as shown in the imag ...

I am utilizing client-side JS to send a large number of requests. What methods can I implement to enable my server to cache this content

Here's a bit of an unusual question from someone who is new to this - I have client-side JavaScript that is making API calls using the getJSON method. Since the content doesn't change frequently, I would like to store the results on my server an ...

Creating a radio button along with a submit button that redirects to a different local HTML file

Can someone please help with this code? I'm trying to redirect to the value of each radio button when it's clicked. Any guidance or JavaScript code would be greatly appreciated. Thank you. I've tried multiple solutions but none of them seem ...