[英]Display dynamically filtered array in Angular
在我的Angular應用程序中
我有一個使用ngFor循環顯示在組件中的數組。
現在,我從數組中過濾數據,並想更新新更新的數組來代替原始數組
我可以在控制台上顯示它,但是我沒有設法在html文件中顯示它。
.TS文件
let arrayTesting = this.arrays.filter(x => x.data === this.data);
console.log(arrayTesting);
.HTML文件
<ion-item *ngFor="let array of arrays">
這是我設法顯示數組但不過濾數據的方法。
這是您的問題的解決方案
您應該首先用另一個變量引用實際的數組,然后對該數組應用過濾器。 不要在HTML中綁定實際的數組,而要綁定過濾后的數組。 這是代碼
的HTML:
<button mat-button (click)="filterList()">Click me!</button>
<ul>
<ul *ngFor="let item of filteredArray">{{item}}</ul>
</ul>
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);
}
}
請發布您的整個TS文件。 在運行該filter方法之前,它可能與頁面呈現有關。 查看ionViewWillEnter()生命周期方法。 我看不到您的代碼,我猜測將您的filter方法放在那里可以正確渲染。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.