簡體   English   中英

渲染所有元素后如何清除aray

[英]How to clear an aray after all it's elemenets have been rendered

我的問題完全與 Angular/Typescript 有關。 我有一個數組,我在 HTML 頁面上使用打印其元素。 代碼還沒有准備好。 我有這樣的事情:

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 e.g. 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/模板

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

在渲染staticKpi后,我想清除數組,以便為下一輪 GET 調用做好准備,否則下一組元素只是添加到前一組元素(連接)。 但在我的情況下,什么都沒有顯示。 我認為它一旦被填充就會被清除。 請指出我的錯誤。

*ngFor="let element of staticKpi"

遍歷staticKpi並顯示該數組內每個元素的模板;

顯示的元素只是當前在數組中的元素,因此如果您打算保留它們,則需要在每次調用后將數據存儲在單獨的數組中,並在模板中迭代該數組;

在 JS Arrays 和 Objects 中保留它們的引用。 因此,如果您在函數之間傳遞數組並且一個 function 編輯數組,其他函數中的所有引用都會受到影響。 所以你需要創建一個新數組。

改變這個:

 this.staticKpi.push(row);

為了這:

this.staticKpi.push([...row]); // there you are creating a new array

現在,你可以做

row = []

並且發送到 staticKpi 的數組副本將保持相等

如果我理解正確,您希望 this.staticKpi 數組在您調用initializeComponent method時具有 0 元素

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

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

    staticKpi = [];
    
    constructor() {
         //super(); // There is no need to do this. This component does not extends another component. 
    }

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

    private initializeComponent() {  
        // First clean the array
        this.staticKpi = [];  
         
        // Anytime you call initializeComponent method, @var row will always be an empty array
        let row = []; // For e.g. Apple, Banana, Mango, etc
        // Join the arrays together or just assign row to staticKpi
        this.staticKpi = [...this.staticKpi,...row];

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM