单击按钮时进行Angular 4过滤

时间:2018-09-20 10:30:04

标签: angular

我是Angular 4中的新手,目前有一个未过滤数据的列表,在左侧,我给出了类别列表。因此,当任何用户单击任何类别时,都应过滤列表。请让我知道我该怎么做?

xyz.component.html

<li *ngFor="let category of categories; let i=index;" (click)="filter(0,category.id)">{{ category.name }}</li>
<div  *ngFor="let post of originalPosts; let i = index">
  <div *ngIf="!post.blogger.team_link">
      {{post.blogger.name}}
 </div>
</div>

xyz.component.ts

  export class BlogComponent implements OnInit {
        filteredPosts=[];
        originalPosts=[];

        constructor(private blogService: BlogService) { 
          this.blogService.getBlogPosts().then(res=>this.originalPosts=res);
        }
        public filter(bgr, cat){
          if(cat != null){
            let category = this.categories[cat]
            this.filteredPosts = this.originalPosts.filter(d => d.category.id == cat);
          }
        }
    }

当前输出显示所有类别 Current Output

预期输出,应仅显示所选类别,例如。作者 Expected Output

无法过滤?

1 个答案:

答案 0 :(得分:0)

这样做

<li *ngFor="let category of categories; let i=index;" (click)="filter(category.id)">{{ category.name }}</li>

组件

originalPosts = []; // add all posts
filteredPosts = [];

public filter(categoryId){  
    this.filteredPosts = this.originalPosts.filter(post => post.category.id === categoryId;
}