[英]What is the right way to filter an array with TypeScript in Angular?
Hello to every one I am new to Angular and I would like to filter an array like this 大家好,我是Angular的新手,我想过滤这样的数组
app.component.ts app.component.ts
export class AppComponent implements OnInit {
columns:string[];
posts: Posts[];
getFilteredData: Posts[];
rows: number;
ngOnInit() {
this.columns = ['userId','id','title','body'];
this.posts = [{userId:1,id:1, title:'Ahmer',body: 'xyz'},{userId:1,id:1, title:'Azeem',body: 'xyz'}]
this.getFilteredData = this.posts;
this.rows = this.getFilteredData.length;
}
onSearching(searchValue: string) {
this.getFilteredData = this.posts.filter((d:Posts ) => {
return d.title.includes(searchValue.toLowerCase())
});
this.rows = this.getFilteredData.length;
}
}
class Posts {
userId: number;
id: number;
title: string;
body: string;
}
app.component.html app.component.html
<input #searchbox placeholder="Search Something" (input)="onSearching($event.target.value)">
<h1>Results</h1>
<br>
<table width="100%" border="1">
<tr>
<th *ngFor="let col of columns">
{{col}}
</th>
</tr>
<tr *ngFor="let data of getFilteredData">
<td *ngFor="let col of columns">
{{data[col]}}
</td>
</tr>
<tr>
<td>
Total Rows:
</td>
<td>
{{rows}}
</td>
</tr>
</table>
output 输出
Question 题
I'm looking for something to filter my JSON Array Object but I don't know why my code doesn't work and show me empty rows. 我在寻找过滤JSON数组对象的方法,但是我不知道为什么我的代码不起作用并向我显示空行。 Please help me to track my mistake.
请帮助我跟踪我的错误。
您还必须将toLowerCase()
应用于过滤器:
return d.title.toLowerCase().includes(searchValue.toLowerCase())
添加到下例到d.title
return d.title.toLowerCase().includes(searchValue.toLowerCase())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.