How to filter an object array using checkbox with angular?

SteveP

I'm currently stuck on a problem with angular. I try to filter an object array using checkbox but it doesn't work. I would try to filter my array by status.

I already try to use "ng-true-value" when i check the checkbox but it seems it doesn't work because of my object array.


mockdata.service.ts :

export class MockDataService {
  House: Array<object> = [];

  constructor() {}

  getHouse() {
    let options = {min:100, max:500}
    const types = ["Maison","Appartement","Bureau","Batiment publique"];
    const status = ["En cours","Prêt à publier","Déjà publié","Informations manquantes"];
    // const status = [1,2,3,4,5];
    for (let i = 0; i < 1; i++) {
      const randomTypes = Math.floor(Math.random()*types.length);
      const randomStatus = Math.floor(Math.random()*status.length);
      this.House.push({
        id: faker.random.uuid(),
        owner: faker.company.companyName(),
        username: faker.internet.userName(),
        street: faker.address.streetAddress(),
        city: faker.address.city(),
        garden: faker.random.number(),
        img: faker.image.city(),
        surface: faker.random.number(options),
        title: faker.lorem.word(),
        type: types[randomTypes],
        projectStatus: status[randomStatus],
        date: faker.date.recent(10)
      });
    }

    return of(this.House);
  }

project-list.component.html :

<input type="checkbox" name="checkbox" [(ngModel)]="checkboxStatus" ng-true-value="'En cours'" ng-false-value="''">
<tr *ngFor="let information of House | filter:searchText | filter:checkboxStatus">

I would like to have 3 checkboxes and when I check a checkbox, the object array displayed as a list should filter by this checkbox.

Thanks for your help !

Joel Joseph

You can do that in the following way :


if you want Single-select


something.component.html

    <input type="checkbox" id="ckb" (change)="onCheck($event,'En cours')"  name="En_cours" value="En cours">
    <tr *ngFor="let information of House | search: searchText | filter: filterKey">

something.component.ts

filterKey: string = '';
searchKeyWord: string = '';
onCheck(event,$value){
  if ( event.target.checked ) {
     this.filterKey= $value;
  }
  else
  {
     this.filterKey= '';
  }
}

search.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {

  transform(items: any, term: any): any {
    if (term === undefined) return items;

    return items.filter(function(item) {
      for(let property in item){

        if (item[property] === null){
          continue;
        }
        if(item[property].toString().toLowerCase().includes(term.toString().toLowerCase())){
          return true;
        }

       }
      return false;
    });
  }

}

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {
  transform(items: any[], filterText: string): any[] {
    if(!items) return [];
    if(!filterText) return items;
filterText = filterText.toLowerCase();
return items.filter( it => {
      return it['projectStatus'].toString().toLowerCase().includes(filterText);
    });
   }

}

If Multi-Select then make few changes to above code :


something.component.html

 <input type="checkbox" id="ckb" (change)="onCheck($event,'En cours')"  name="En_cours" value="En cours">
 <tr *ngFor="let information of House | search: searchText | filter: filterKeys">

something.component.ts

filterKeys = [];
searchKeyWord: string = '';
onCheck(event,$value){
  if ( event.target.checked ) {
     this.filterKeys.push($value);
  }
  else
  {
     this.filterKeys.splice(this.filterKeys.indexOf($value), 1);
  }
}

filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {
  transform(array: any[], query:string[]):any[] {
  if (typeof array === 'object') {
   var resultArray = [];
   if (query.length === 0) {
     resultArray = array;
   }
   else {
     resultArray = (array.filter(function (a) {
      return ~this.indexOf(a.projectStatus);
    }, query));
   }
   return resultArray;
 }
 else {
  return null;
  }
 }

}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

How to filter an array using angular js

How do I filter a list sorted from Checkbox Values in Angular?

Observable of array with filter using Angular 5 with RxJS

How to filter markers on a Gmaps object with angular and javascript

How to filter nested object not equal in Angular?

How to filter an array of objects based on a particular object?

How can I get a specific value from my JSON object without using Array.filter()?

How to filter out objects from array of object on the basics of object id

How to filter an array that excludes from object's property array

How to add to an array using angular?

Filter array in angular

Filter the list items using checkbox in vue

searching using angular filter

How using object pointer with dynamic array

How to convert an array into an object using stdClass()

How to filter and get each object key's value using startsWith?

Search/Filter JavaScript Object Array

How to use checkbox input to filter results?

How to filter object data?

How To Show Data From A Nested Array Using Mongoose Filter?

how to transpose object of array in single object using DataWeave

How to access Array Object without key name in HTML with Angular

Making an Angular filter using $http?

How to format the value of a checkbox Field using React Final Form Field Array?

How to correctly bind checkbox to the object list in thymeleaf?

how to filter json object data?

How can I filter rows if one array contains all values from another array using BigQuery?

filter object by property that starts with any of array elements

Filter response object based on an array of whitelisted ids

TOP 一覧

  1. 1

    PictureBoxで画像のブレンドを無効にする

  2. 2

    HTTPヘッダー 'SOAPAction'の値はサーバーによって認識されませんでした

  3. 3

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  4. 4

    レスポンシブウェブサイトの一番下にスティッキーなナビゲーションバーを作成するのに問題がある

  5. 5

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  6. 6

    Ansibleで複数行のシェルスクリプトを実行する方法

  7. 7

    Python / SciPyのピーク検出アルゴリズム

  8. 8

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  9. 9

    ZScalerと証明書の問題により、Dockerを使用できません

  10. 10

    Rパッケージ「AppliedPredictiveModeling」のインストール中にエラーが発生しました

  11. 11

    テキストフィールドの値に基づいて UIslider を移動します

  12. 12

    Crashlytics:コンパイラー生成とはどういう意味ですか?

  13. 13

    「埋め込みブラウザのOAuthログイン」を有効にしてコールバックURLを指定した後でも、Facebookのコールバックエラーが発生する

  14. 14

    tf.nn_conv2dとtf.nn.depthwise_conv2dの違い

  15. 15

    CSSはアニメーションで変換および回転します

  16. 16

    BLOBストレージからデータを読み取り、Azure関数アプリを使用してデータにアクセスする方法

  17. 17

    Chromeウェブアプリのウェブビューの高さの問題

  18. 18

    Postmanを使用してファイル付きの(ネストされた)jsonオブジェクトを送信する

  19. 19

    amCharts 4で積み上げ棒グラフの輪郭を描く方法は?

  20. 20

    Officeアドインを使用してOutlookの連絡先のリストにプログラムでアクセスすることは可能ですか?

  21. 21

    Reactでclsxを使用する方法

ホットタグ

アーカイブ