首页 > 解决方案 > 使用角度材料复选框根据类别过滤课程

问题描述

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

示例: javascript是课程名称,脚本category

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

在此处输入图像描述

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

标签: angular-materialangular6

解决方案


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

OnInit, 设置filteredCoursescourses所以它在初始化时将它们全部呈现。

 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


推荐阅读