在Angular中使用TypeScript过滤数组的正确方法是什么?

时间:2018-04-24 15:15:54

标签: json angular typescript

大家好,我是Angular的新手,我想像这样过滤一个数组

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

<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>

输出

enter image description here

问题

我正在寻找过滤我的JSON数组对象的东西,但我不知道为什么我的代码不起作用并向我显示空行。请帮我跟踪我的错误。

2 个答案:

答案 0 :(得分:4)

您还必须将toLowerCase()应用于您的过滤器:

return d.title.toLowerCase().includes(searchValue.toLowerCase())

答案 1 :(得分:1)

将toLowerCase添加到d.title

return d.title.toLowerCase().includes(searchValue.toLowerCase())

相关问题