简体   繁体   English

在Angular中显示动态过滤的数组

[英]Display dynamically filtered array in Angular

In my Angular Application 在我的Angular应用程序中

I have an array that is displayed in the component using an ngFor loop. 我有一个使用ngFor循环显示在组件中的数组。

Now I filter the data from the array and would like to update the newly updated array in place of the original array 现在,我从数组中过滤数据,并想更新新更新的数组来代替原始数组

I can display it on the console but I didn't manage to display it on my html file. 我可以在控制台上显示它,但是我没有设法在html文件中显示它。

.TS file .TS文件

 let arrayTesting = this.arrays.filter(x => x.data === this.data);
 console.log(arrayTesting);

.HTML file .HTML文件

<ion-item *ngFor="let array of arrays">

Here is the way i manage to display an array but without filtering my data. 这是我设法显示数组但不过滤数据的方法。

Here is a solution to your problem 这是您的问题的解决方案

You should first reference your actual array with another variable and apply filter on that array. 您应该首先用另一个变量引用实际的数组,然后对该数组应用过滤器。 DO not bind the actual array in the HTML but the filtered one . 不要在HTML中绑定实际的数组,而要绑定过滤后的数组。 Here is the code 这是代码

html: 的HTML:

<button mat-button (click)="filterList()">Click me!</button>

<ul>
<ul  *ngFor="let item of filteredArray">{{item}}</ul>
</ul>

Ts file: ts文件:

import {Component} from '@angular/core';

/**
 * @title Basic buttons
 */
@Component({
  selector: 'button-overview-example',
  templateUrl: 'button-overview-example.html',
  styleUrls: ['button-overview-example.css'],
})
export class ButtonOverviewExample {

 array: number[]=[];
 filteredArray:number[]=[];


 ngOnInit(){
   this.array.push(1);
      this.array.push(2);
         this.array.push(3);
            this.array.push(4);

     for(let i=0;i<this.array.length;i++){
        this.filteredArray.push(this.array[i]);
     }

 }

 filterList(){
   this.filteredArray=this.array.filter(x => x === 2);
 }

}

You can run this code by replacing all the code here 您可以通过在此处替换所有代码运行此代码

Please post your whole TS file. 请发布您的整个TS文件。 It likely has to do with the page rendering before that filter method is run. 在运行该filter方法之前,它可能与页面呈现有关。 Look into the ionViewWillEnter() lifecycle method. 查看ionViewWillEnter()生命周期方法。 Without seeing your code, it is my guess that putting your filter method in there will render correctly. 我看不到您的代码,我猜测将您的filter方法放在那里可以正确渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM