根据类别使用角度材料复选框过滤课程

问题描述 投票:0回答:1

我有两个名为1.Courses和2.Categories的数组,每个课程都有不同的类别,我想使用mat-checkbox按类别过滤课程。

示例:javascript是课程名称,脚本是类别。

这是stackblitz link,下面是该方法的屏幕截图:

enter image description here

它应该适用于多个复选框过滤谢谢你提前。

angular-material angular6
1个回答
1
投票

因此,使用当前方法IMO执行此操作的最简单方法是创建一个新的课程数组filteredCourses并在模板中迭代它。

OnInit,将filteredCourses设置为courses,因此它将它们全部呈现在init上。

 ngOnInit() {
   this.filteredCourses = this.courses;
 }

接下来,您需要一些方法来维护所选类别的列表。如果您使用Angulars内置的形式,这将更容易,但是,如果没有,我可以建议以下内容:

onSelect(点击),将点击的类别添加到所选类别的列表中(点击,如果它不在那里,添加它,否则,删除它)

onSelect(selectedCategory: any) {
   this.selectCategory(selectedCategory);  
}

selectCategory(selectedCategory: any) {
   const index: number = this.selectedCategories.findIndex((cat: any) => { 
     return cat.id === selectedCategory.id 
   });

   if ( index === -1) {
      this.selectedCategories.push(selectedCategory);
   } else {
      this.selectedCategories.splice(index, 1);
   }
}

接下来的步骤是将courses数组过滤到categoryId列表中包含selectedCategories的那些数组,并将filteredCourses数组设置为结果,允许模板更新。所以,你的onSelect功能变为:

onSelect(selectedCategory: any) {
   this.selectCategory(selectedCategory);
   this.filteredCourses = this.courses.filter((course: any) => {
     return this.selectedCategories.findIndex((cat: any) => {
        return course.categoryId === cat.id;
     }) !== -1;
   });
 }

更新闪电战的建议:https://stackblitz.com/edit/mat-checkbox-kq6xgd

© www.soinside.com 2019 - 2024. All rights reserved.