如何为列表添加多个过滤器,并在角度7中分别取消选中它们? [英] How to add Multiple filter for a list and uncheck them individually in angular 7?

查看:43
本文介绍了如何为列表添加多个过滤器,并在角度7中分别取消选中它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 7和3按钮中有一个使用ngFor填充的复选框列表来过滤该复选框列表,我目前只能过滤一次.我想做的是添加多个过滤器,例如如果我单击complted按钮我应该还允许单击活动"和任何其他按钮,并且列表应仅过滤那些过滤器.最后,也应允许我也取消其单击过滤器.我的代码如下:

我的ts文件

 从'@ angular/core'导入{Component,OnInit};@零件({选择器:"app-checkboxexample",templateUrl:"./checkboxexample.component.html",styleUrls:['./checkboxexample.component.scss']})导出类CheckboxexampleComponent实现了OnInit {selectedItemsList = [];CheckedIDs = [];过滤器:字符串;num1:任何;checkboxesDataList = [{id:"C001",标签:摄影",isChecked:否,完成:错误},{id:"C002",标签:写作",isChecked:否,完成:正确},{id:"C003",标签:绘画",isChecked:否,完成:错误},{id:"C004",标签:针织",isChecked:否,完成:错误},{id:"C011",标签:跳舞",isChecked:否,完成:正确},{id:"C005",标签:园艺",isChecked:否,完成:错误},{id:"C006",标签:绘图",isChecked:否,完成:正确},{id:"C007",标签:健身房",isChecked:否,完成:正确},{id:"C008",标签:烹饪",isChecked:否,完成:正确},{id:"C009",标签:剪贴簿",isChecked:否,完成:错误},{id:"C010",标签:折纸",isChecked:否,完成:错误}]ngOnInit():void {如果(sessionStorage.getItem('screening')!= null){this.selectedItemsList = JSON.parse(sessionStorage.getItem('screening'));this.checkboxesDataList = this.selectedItemsListthis.num1 = JSON.parse(sessionStorage.getItem('manual'))}this.filter ='全部';this.fetchSelectedItems()this.fetchCheckedIDs()}changeSelection(){this.fetchSelectedItems()}fetchSelectedItems(){this.selectedItemsList = this.checkboxesDataList.filter((value,index)=> {返回值});}fetchCheckedIDs(){this.checkedIDs = []this.checkboxesDataList.forEach((value,index)=> {如果(value.isChecked){this.checkedIDs.push(value.id);}});}deleteTodo(id:字符串):void {this.selectedItemsList = this.selectedItemsList.filter(item => item.id!== id);this.checkboxesDataList.forEach(element => {如果(element.id == id.toString()){element.isChecked = false;}});}onsubmit(){this.num1 =((document.getElementById("manual")as HTMLInputElement).value);sessionStorage.setItem('manual',JSON.stringify(this.num1));sessionStorage.setItem('screening',JSON.stringify(this.checkboxesDataList))}todosFiltered(){如果(this.filter ==='all'){返回this.checkboxesDataList;} else if(this.filter ==='editing'){返回this.checkboxesDataList.filter(todo =>!todo.completed);} else if(this.filter ==='completed'){返回this.checkboxesDataList.filter(todo => todo.completed);}返回this.checkboxesDataList;}} 

我的html文件

 < h1>检查清单</h1>< div class =额外容器">< div class ="card"style ="width:18rem; padding-left:2%;"< ul class ="list-group list-group-flush">< li class =列表组项目"><按钮[ngClass] ="{{active:filter ==='all'}""(click)="filter ='all'"> All</button></li>< li class =列表组项目"><按钮[ngClass] ="{{active:filter ==='editing'}'"(点击)=过滤器='编辑'">活动</按钮></li>< li class =列表组项目"><按钮[ngClass] =" {{active:filter ==='completed'}'(点击)=过滤器=完成""/已完成"/按钮"</li></ul></div>< div class ="row">< div class ="col-md-4">< h4>兴趣爱好列表//h4>< ul class ="checkbox-items">< li * ngFor ="让todosFiltered().slice(0,7)的项保持不变.<输入类型=复选框";name ="id ="[(ngModel)] ="item.isChecked";(change)="changeSelection()"> {{item.label}}</li>< li * ngFor =" todosFiltered().slice(7,14)的项"><输入类型=复选框";name ="id ="[(ngModel)] ="item.isChecked";(change)="changeSelection()"> {{item.label}}</li></ul></div>< div class ="col-md-4">< h4>所选兴趣爱好的数量:{{selectedItemsList.length}}<输入类型=文本";id ="manual"值= {{num1}}></h4>< ul>< li * ngFor =选择的项目列表中的项目"> {{item.label}}< div class =删除项目"(点击)="deleteTodo(item.id)"& times;</div></li></ul></div>< div class ="col-md-4">< h4>对象</h4>< code>{{selectedItemsList |json}}</code>< h4> ID数组//h4>< code> {{checkedIDs}}</code></div></div>< button type =提交";(点击)="onsubmit()"> Submit</button> 

解决方案

如果要应用多个过滤器,我将使每个切换开关更新其自己的过滤器状态.然后,您可以将多个过滤器应用于数组并返回结果.您的过滤器方法如下所示:

  todosFiltered(){让checkboxesToDisplay = this.checkboxesDataList;如果(this.filterActive){checkboxesToDisplay = checkboxesToDisplay.filter(todo =>!todo.completed);}如果(this.filterCompleted){checkboxesToDisplay = checkboxesToDisplay.filter(todo => todo.completed);}返回checkboxesToDisplay;} 

然后每个按钮可以切换这些过滤器,全部"按钮可以将其设置为false.

 < li class ="列表组项目"><按钮[ngClass] =" {'active':filter ==='all'}"(点击)="filterActive = false; filterCompleted = false">全部</button></li>< li class =列表组项目"><按钮[ngClass] ="{{active:filter ==='editing'}'"(点击)="filterActive =!filterActive"> Active</button></li>< li class =列表组项目"><按钮[ngClass] =" {{active:filter ==='completed'}'(点击)="filterCompleted =!filterCompleted">已完成</button></li>. 

我进行了一些快速更改,使您更接近所要寻找的行为:

stackblitz

I have a checkbox list populated using ngFor in Angular 7 and 3 buttons to filter the checkbox list,I am able to filter only once currently.What i want to do it to add multiple filters like if i click complted button i should also be allowed to click Active and any other button and the list should filter only those.Lastly i should be allowed to undo the filters on its clicks as well.THANKS A LOT IN ADVANCE. My code is below:

My ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-checkboxexample',
  templateUrl: './checkboxexample.component.html',
  styleUrls: ['./checkboxexample.component.scss']
})
export class CheckboxexampleComponent implements OnInit {

  selectedItemsList = [];
  checkedIDs = [];
  filter: string;
  num1: any;



  checkboxesDataList = [
    {
      id: 'C001',
      label: 'Photography',
      isChecked: false,
      completed: false
    },
    {
      id: 'C002',
      label: 'Writing',
      isChecked: false,
      completed: true
    },
    {
      id: 'C003',
      label: 'Painting',
      isChecked: false,
      completed: false
    },
    {
      id: 'C004',
      label: 'Knitting',
      isChecked: false,
      completed: false
    },
    {
      id: 'C011',
      label: 'Dancing',
      isChecked: false,
      completed: true
    },
    {
      id: 'C005',
      label: 'Gardening',
      isChecked: false,
      completed: false
    },
    {
      id: 'C006',
      label: 'Drawing',
      isChecked: false,
      completed: true
    },
    {
      id: 'C007',
      label: 'Gyming',
      isChecked: false,
      completed: true
    },
    {
      id: 'C008',
      label: 'Cooking',
      isChecked: false,
      completed: true
    },
    {
      id: 'C009',
      label: 'Scrapbooking',
      isChecked: false,
      completed: false
    },
    {
      id: 'C010',
      label: 'Origami',
      isChecked: false,
      completed: false
    }
  ]

  ngOnInit(): void {
    if (sessionStorage.getItem('screening') != null) {
      this.selectedItemsList = JSON.parse(sessionStorage.getItem('screening'));
      this.checkboxesDataList = this.selectedItemsList
      this.num1 = JSON.parse(sessionStorage.getItem('manual'))
    }
    this.filter = 'all';
    this.fetchSelectedItems()
    this.fetchCheckedIDs()

  }

  changeSelection() {
    this.fetchSelectedItems()

  }

  fetchSelectedItems() {
    this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {

      return value.isChecked
    });
  }

  fetchCheckedIDs() {
    this.checkedIDs = []
    this.checkboxesDataList.forEach((value, index) => {
      if (value.isChecked) {
        this.checkedIDs.push(value.id);
      }
    });
  }
  deleteTodo(id: string): void {
    this.selectedItemsList = this.selectedItemsList.filter(item => item.id !== id);
    this.checkboxesDataList.forEach(element => {
      if (element.id == id.toString()) {
        element.isChecked = false;
      }
    });
  }
  onsubmit() {
    this.num1 = ((document.getElementById("manual") as HTMLInputElement).value);
    sessionStorage.setItem('manual', JSON.stringify(this.num1));
    sessionStorage.setItem('screening', JSON.stringify(this.checkboxesDataList))
  }
  todosFiltered() {
    if (this.filter === 'all') {
      return this.checkboxesDataList;
    } else if (this.filter === 'editing') {
      return this.checkboxesDataList.filter(todo => !todo.completed);
    } else if (this.filter === 'completed') {
      return this.checkboxesDataList.filter(todo => todo.completed);
    }

    return this.checkboxesDataList;
  }

}

My html file

<h1>Checklist</h1>
<div class="extra-container">
    <div class="card" style="width: 18rem;padding-left: 2%;">
        <ul class="list-group list-group-flush">
            <li class="list-group-item"><button [ngClass]="{'active': filter === 'all'}"
                    (click)="filter='all'">All</button></li>
            <li class="list-group-item"><button [ngClass]="{'active': filter === 'editing'}"
                    (click)="filter='editing'">Active</button></li>
            <li class="list-group-item"><button [ngClass]="{'active': filter === 'completed'}"
                    (click)="filter='completed'">Completed</button></li>
        </ul>
    </div>

    <div class="row">

        <div class="col-md-4">
            <h4>List of Hobbies</h4>



            <ul class="checkbox-items">
                <li *ngFor="let item of todosFiltered().slice(0,7)">

                    <input type="checkbox" name="" id="" [(ngModel)]="item.isChecked"
                        (change)="changeSelection()">{{item.label}}

                </li>
                <li *ngFor="let item of todosFiltered().slice(7,14)">

                    <input type="checkbox" name="" id="" [(ngModel)]="item.isChecked"
                        (change)="changeSelection()">{{item.label}}

                </li>
            </ul>

        </div>

        <div class="col-md-4">
            <h4>No of Selected Hobbies: {{selectedItemsList.length}}
                <input type="text" id="manual" value={{num1}}> </h4>
            <ul>
                <li *ngFor="let item of selectedItemsList">{{item.label}}
                    <div class="remove-item" (click)="deleteTodo(item.id)">
                        &times;
                    </div>
                </li>

            </ul>

        </div>

        <div class="col-md-4">
            <h4>Object</h4>
            <code>
    {{selectedItemsList | json}} 
    </code>

            <h4>Array of IDs</h4>
            <code>{{checkedIDs}}</code>
        </div>

    </div>
    <button type="submit" (click)="onsubmit()">Submit</button>

解决方案

If you want to apply multiple filters, I would make each toggle update its own filter state. Then you could apply multiple filters to your array and return the result. Your filter method would look something like:

todosFiltered() {
    let checkboxesToDisplay = this.checkboxesDataList;

    if (this.filterActive) {
      checkboxesToDisplay = checkboxesToDisplay.filter(todo => !todo.completed);
    }

    if (this.filterCompleted) {
      checkboxesToDisplay = checkboxesToDisplay.filter(todo => todo.completed);
    }

    return checkboxesToDisplay;
  }

Then each button could toggle those filters and the 'All' button could set them to false.

<li class="list-group-item"><button [ngClass]="{'active': filter === 'all'}"
                    (click)="filterActive=false;filterCompleted=false">All</button></li>
<li class="list-group-item"><button [ngClass]="{'active': filter === 'editing'}"
                    (click)="filterActive=!filterActive">Active</button></li>
<li class="list-group-item"><button [ngClass]="{'active': filter === 'completed'}"
                    (click)="filterCompleted=!filterCompleted">Completed</button></li>

I made some quick changes that should get you closer to the behavior you are looking for:

stackblitz

这篇关于如何为列表添加多个过滤器,并在角度7中分别取消选中它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆