Jak zastosować filtry do * ngFor?

Najwyraźniej Angular 2 będzie używał rur zamiast filtrów, jak w Angular1 w połączeniu z ng-for do filtrowania wyników, chociaż implementacja nadal wydaje się niejasna, bez jasnej dokumentacji.

Mianowicie to, co staram się osiągnąć, można zobaczyć z następującej perspektywy

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

Jak zaimplementować Tak używając rur?

Author: Stefan Falk, 2015-12-08

23 answers

Zasadniczo piszesz rurę, którą możesz następnie użyć w dyrektywie *ngFor.

W składniku:

filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];

W szablonie możesz przekazać ciąg, liczbę lub obiekt do swojej rury, aby użyć go do filtrowania:

<li *ngFor="let item of items | myfilter:filterargs">

In your pipe:

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

@Pipe({
    name: 'myfilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: Object): any {
        if (!items || !filter) {
            return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(item => item.title.indexOf(filter.title) !== -1);
    }
}

Pamiętaj, aby zarejestrować rurkę w app.module.ts; nie musisz już rejestrować rur w swoim @Component

import { MyFilterPipe } from './shared/pipes/my-filter.pipe';

@NgModule({
    imports: [
        ..
    ],
    declarations: [
        MyFilterPipe,
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Oto Plunker , który demonstruje użycie niestandardowej rury filtracyjnej i wbudowanej rury slice, aby ograniczyć wyniki.

Proszę zauważyć (jak zauważyło kilku komentatorów), że istnieje powód, dla którego nie ma wbudowanych rur filtrujących w kąt.

 434
Author: phuc77,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 15:30:50

Wielu z Was ma świetne podejście, ale celem tutaj jest być ogólnym i zdefiniowanie rury tablicy, która jest niezwykle wielokrotnego użytku we wszystkich przypadkach w odniesieniu do * ngFor.

/ align = "left" / rura.ts (nie zapomnij dodać tego do tablicy deklaracji twojego modułu)

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

@Pipe({
    name: 'callback',
    pure: false
})
export class CallbackPipe implements PipeTransform {
    transform(items: any[], callback: (item: any) => boolean): any {
        if (!items || !callback) {
            return items;
        }
        return items.filter(item => callback(item));
    }
}

Następnie w Twoim komponencie musisz zaimplementować metodę o następującej signuature (item: any) = > boolean, w moim przypadku na przykład nazwałem ją filterUser, która filtruje wiek użytkowników, który jest powyżej 18 lat.

Twój Komponent

@Component({
  ....
})
export class UsersComponent {
  filterUser(user: IUser) {
    return !user.age >= 18
  }
}

I ostatni, ale nie mniej ważny, Twój kod html będzie wyglądał tak:

Twój HTML

<li *ngFor="let user of users | callback: filterUser">{{user.name}}</li>

Jak widać, ta rura jest dość ogólna dla wszystkich tablic, jak elementy, które muszą być filtrowane przez wywołanie zwrotne. W mycase okazało się, że jest to bardzo przydatne dla *ngFor jak scenariusze.

Mam nadzieję, że to pomoże!!!

Codematrix

 123
Author: code5,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-12 20:52:36

Sposób uproszczony (używany tylko na małych tablicach ze względu na problemy z wydajnością. W dużych tablicach musisz zrobić filtr ręcznie za pomocą kodu):

Zobacz: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field : string, value : string): any[] {  
      if (!items) return [];
      if (!value || value.length == 0) return items;
      return items.filter(it => 
      it[field].toLowerCase().indexOf(value.toLowerCase()) !=-1);
    }
}

Użycie:

<li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>

Jeśli używasz zmiennej jako drugiego argumentu, nie używaj cudzysłowów.

 39
Author: Rodolfo Jorge Nemer Nogueira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-15 17:48:23

To jest to, co zaimplementowałem bez użycia pipe.

Komponent.html

<div *ngFor="let item of filter(itemsList)">

Komponent.ts

@Component({
....
})
export class YourComponent {
  filter(itemList: yourItemType[]): yourItemType[] {
    let result: yourItemType[] = [];
    //your filter logic here
    ...
    ...
    return result;
  }
}
 32
Author: Thang Le,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-12 11:47:31

Nie jestem pewien, kiedy to przyszło, ale już zrobili rurkę, która to zrobi. To też jest dobrze udokumentowane.

Https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

<p *ngFor="let feature of content?.keyFeatures | slice:1:5">
   {{ feature.description }}
</p>
 19
Author: SpaceBeers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-14 04:41:44

Możesz również użyć:

<template ngFor let-item [ngForOf]="itemsList">
    <div *ng-if="conditon(item)"></div>
</template>

Wyświetli div tylko wtedy, gdy twoje elementy pasują do warunku

Zobacz dokumentację kątową aby uzyskać więcej informacji Jeśli potrzebujesz również indeksu, użyj następującego:

<template ngFor let-item [ngForOf]="itemsList" let-i="index">
    <div *ng-if="conditon(item, i)"></div>
</template>
 11
Author: Jeroen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-18 15:15:49

Rury w Angular2 są podobne do rur w wierszu poleceń. Wyjście każdej poprzedzającej wartości jest podawane do filtra za rurą, co ułatwia łańcuchowanie filtrów w następujący sposób:

<template *ngFor="#item of itemsList">
    <div *ngIf="conditon(item)">{item | filter1 | filter2}</div>
</template>
 9
Author: Ben Glasser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-12 18:54:07

Wiem, że to stare pytanie, jednak pomyślałem, że może być pomocne, aby zaoferować inne rozwiązanie.

Odpowiednik AngularJS tego

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

W Angular 2+ nie można użyć *ngFor i * ngIf na tym samym elemencie, więc będzie to następujące:

<div *ngFor="let item of itemsList">
     <div *ngIf="conditon(item)">
     </div>
</div>

A jeśli nie możesz użyć jako wewnętrznego kontenera, użyj zamiast tego ng-container. ng-container jest przydatny, gdy chcesz warunkowo dołączyć grupę elementów (np. używając *ngif="foo") w aplikacji, ale nie chcesz ich zawijać kolejny element.

 7
Author: tgralex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-17 15:24:51

Proste rozwiązanie, które działa z Angular 6 do filtrowania ngFor, jest następujące:

<span *ngFor="item of itemsList"  >
  <div *ngIf="yourCondition(item)">
    
    your code
    
  </div>
</span

Przęsła są użyteczne, ponieważ nie reprezentują niczego z natury.

 6
Author: Michael V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-19 02:10:07

Dla tego wymogu, implementuję i publikuję komponent ogólny. Zobacz

Https://www.npmjs.com/package/w-ng5

Aby użyć tego komponentu, przed zainstalowaniem tego pakietu z npm:

npm install w-ng5 --save

Po zaimportowaniu modułu w aplikacji.Moduł

...
import { PipesModule } from 'w-ng5';

W następnym kroku dodaj w sekcji declare aplikacji.Moduł:

imports: [
  PipesModule,
  ...
]

Przykładowe użycie

Filtrowanie prostego ciągu

<input type="text"  [(ngModel)]="filtroString">
<ul>
  <li *ngFor="let s of getStrings() | filter:filtroString">
    {{s}}
  </li>
</ul>

Filtrowanie złożonego ciągu - pole "Wartość" w poziomie 2

<input type="text"  [(ngModel)]="search">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtering complex string-middle field - 'Value' in level 1

<input type="text"  [(ngModel)]="search3">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.valor1', value: search3}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtering complex array simple-field 'Nome' level 0

<input type="text"  [(ngModel)]="search2">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'nome', value: search2}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtrowanie w polach drzewa-pole "Valor" na poziomie 2 lub "Valor" na poziomie 1 lub "Nome" na poziomie 0

<input type="text"  [(ngModel)]="search5">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search5}, {field:'n1.valor1', value: search5}, {field:'nome', value: search5}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Filtrowanie nieistniejącego pola - 'Valor' w nieistniejącym poziomie 3

<input type="text"  [(ngModel)]="search4">
<ul>
  <li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.n3.valor3', value: search4}]">
    {{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
  </li>
</ul>

Ten komponent działa z nieskończonym atrybutem poziom...

 5
Author: Wedson Quintanilha da Silva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-28 00:32:14

Rura byłaby najlepszym podejściem. ale poniżej jeden też by zadziałał.

<div *ng-for="#item of itemsList">
  <ng-container *ng-if="conditon(item)">
    // my code
  </ng-container>
</div>
 4
Author: Hardik Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-07 09:10:24

Stworzyłem plunker na podstawie odpowiedzi tu i gdzie indziej.

Dodatkowo musiałem dodać @Input, @ViewChild, i ElementRef z <input> i utworzyć i subscribe() do obserwowalnego z niego.

Angular2 Filtr wyszukiwania: PLUNKR (Aktualizacja: plunker już nie działa)

 4
Author: Nate May,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-31 22:03:42

W oparciu o bardzo eleganckie rozwiązanie rury zwrotnej zaproponowane powyżej, można je nieco uogólnić, umożliwiając przekazywanie dodatkowych parametrów filtra. Mamy wtedy:

/ align = "left" / rura.ts

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

@Pipe({
  name: 'callback',
  pure: false
})
export class CallbackPipe implements PipeTransform {
  transform(items: any[], callback: (item: any, callbackArgs?: any[]) => boolean, callbackArgs?: any[]): any {
    if (!items || !callback) {
      return items;
    }
    return items.filter(item => callback(item, callbackArgs));
  }
}

Komponent

filterSomething(something: Something, filterArgs: any[]) {
  const firstArg = filterArgs[0];
  const secondArg = filterArgs[1];
  ...
  return <some condition based on something, firstArg, secondArg, etc.>;
}

Html

<li *ngFor="let s of somethings | callback : filterSomething : [<whatWillBecomeFirstArg>, <whatWillBecomeSecondArg>, ...]">
  {{s.aProperty}}
</li>
 2
Author: Blablalux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-11 10:43:18

To jest mój kod:

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

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field : string, value): any[] {
      if (!items) return [];
      if (!value || value.length === 0) return items;
      return items.filter(it =>
      it[field] === value);
    }
}

Próbka:

LIST = [{id:1,name:'abc'},{id:2,name:'cba'}];
FilterValue = 1;

<span *ngFor="let listItem of LIST | filter : 'id' : FilterValue">
                              {{listItem .name}}
                          </span>
 2
Author: Pàldi Gergő,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-08 21:06:57

Innym podejściem, które lubię używać dla filtrów specyficznych dla aplikacji, jest użycie niestandardowej właściwości tylko do odczytu na komponencie, która pozwala na hermetyzację logiki filtrowania bardziej czysto niż przy użyciu niestandardowej rury (IMHO).

Na przykład, jeśli chcę połączyć się z albumList i filtrować na searchText:

searchText: "";
albumList: Album[] = [];

get filteredAlbumList() {
    if (this.config.searchText && this.config.searchText.length > 1) {
      var lsearchText = this.config.searchText.toLowerCase();
      return this.albumList.filter((a) =>
        a.Title.toLowerCase().includes(lsearchText) ||
        a.Artist.ArtistName.toLowerCase().includes(lsearchText)
      );
    }
    return this.albumList;
}

Aby związać w HTML, możesz następnie powiązać z właściwością tylko do odczytu:

<a class="list-group-item"
       *ngFor="let album of filteredAlbumList">
</a>

Uważam, że dla specjalistycznych filtrów, które są specyficzne dla aplikacji, działa to lepiej niż rura, ponieważ zachowuje logikę związaną z filtrem z komponentem.

Rury działają lepiej dla filtrów wielokrotnego użytku.

 1
Author: Rick Strahl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-03 22:39:09

Utworzyłem poniższy kanał, aby uzyskać pożądane elementy z listy.

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(items: any[], filter: string): any {
    if(!items || !filter) {
      return items;
    }
    // To search values only of "name" variable of your object(item)
    //return items.filter(item => item.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1);

    // To search in values of every variable of your object(item)
    return items.filter(item => JSON.stringify(item).toLowerCase().indexOf(filter.toLowerCase()) !== -1);
  }

}

Konwersja małych liter jest po prostu dopasowana w sposób niewrażliwy na wielkość liter. Możesz go użyć w swoim widoku tak: -

<div>
  <input type="text" placeholder="Search reward" [(ngModel)]="searchTerm">
</div>
<div>
  <ul>
    <li *ngFor="let reward of rewardList | filter:searchTerm">
      <div>
        <img [src]="reward.imageUrl"/>
        <p>{{reward.name}}</p>
      </div>
    </li>
  </ul>
</div>
 1
Author: Sanchit Tandon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-25 10:47:24

Najlepiej stworzyć do tego rurkę angualr 2. Ale możesz zrobić tę sztuczkę.

<ng-container *ngFor="item in itemsList">
    <div*ngIf="conditon(item)">{{item}}</div>
</ng-container>
 1
Author: Peter Huang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 16:13:09

Oto przykład, który stworzyłem jakiś czas temu i o którym pisałem na blogu, który zawiera działający plunk. Zapewnia rurę filtrującą, która może filtrować dowolną listę obiektów. Zasadniczo wystarczy podać właściwość i wartość {klucz: wartość} w specyfikacji ngFor.

Niewiele różni się od odpowiedzi @NateMay, poza tym, że wyjaśniam to stosunkowo szczegółowo.

W moim przypadku przefiltrowałem nieuporządkowaną listę na jakimś tekście (filterText), który użytkownik wpisał na etykiecie " label" właściwość obiektów w tablicy o takim oznaczeniu:

<ul>
  <li *ngFor="let item of _items | filter:{label: filterText}">{{ item.label }}</li>
</ul>

Https://long2know.com/2016/11/angular2-filter-pipes/

 0
Author: long2know,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-17 03:22:23

Pierwszy krok tworzysz Filtr używając @Pipe w swoim komponencie.plik ts:

Twoje.komponent.ts

import { Component, Pipe, PipeTransform, Injectable } from '@angular/core';
import { Person} from "yourPath";

@Pipe({
  name: 'searchfilter'
})
@Injectable()
export class SearchFilterPipe implements PipeTransform {
  transform(items: Person[], value: string): any[] {
    if (!items || !value) {
      return items;
    }
    console.log("your search token = "+value);
    return items.filter(e => e.firstName.toLowerCase().includes(value.toLocaleLowerCase()));
  }
}
@Component({
  ....
    persons;

    ngOnInit() {
         //inicial persons arrays
    }
})

I struktura danych obiektu Person:

Osób.ts

export class Person{
    constructor(
        public firstName: string,
        public lastName: string
    ) { }
}

W Twoim widoku w pliku html:

Twoje.komponent.html

    <input class="form-control" placeholder="Search" id="search" type="text" [(ngModel)]="searchText"/>
    <table class="table table-striped table-hover">
      <colgroup>
        <col span="1" style="width: 50%;">
        <col span="1" style="width: 50%;">
      </colgroup>
      <thead>
        <tr>
          <th>First name</th>
          <th>Last name</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let person of persons | searchfilter:searchText">
          <td>{{person.firstName}}</td>
          <td>{{person.lastName}}</td>
        </tr>
      </tbody>
    </table>
 0
Author: Piotr R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-22 18:02:06

To jest Twoja tablica

products: any = [
        {
            "name": "John-Cena",
                    },
        {
            "name": "Brock-Lensar",

        }
    ];

To jest twoja pętla ngFor Filtruj Według:

<input type="text" [(ngModel)]='filterText' />
    <ul *ngFor='let product of filterProduct'>
      <li>{{product.name }}</li>
    </ul>

Tam używam filterproduct instant of products, ponieważ chcę zachować moje oryginalne dane. Tutaj model _filterText jest używany jako pole wprowadzania.Gdy kiedykolwiek pojawi się jakakolwiek funkcja setter zmiany będzie wywoływać. W wywołaniu setFilterText performProduct zwróci wynik tylko tym, którzy pasują do danych wejściowych. Używam małych liter do niewrażliwości na małe litery.

filterProduct = this.products;
_filterText : string;
    get filterText() : string {
        return this._filterText;
    }

    set filterText(value : string) {
        this._filterText = value;
        this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;

    } 

    performProduct(value : string ) : any {
            value = value.toLocaleLowerCase();
            return this.products.filter(( products : any ) => 
                products.name.toLocaleLowerCase().indexOf(value) !== -1);
        }
 0
Author: Gajender Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 09:58:26

Po jakimś googlowaniu natknąłem się ng2-search-filter. In weźmie Twój obiekt i zastosuje wyszukiwany termin względem wszystkich właściwości obiektu szukających dopasowania.

 0
Author: alindber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-16 20:23:27

Znalazłem coś do zrobienia filtra przechodzącego przez obiekt, wtedy mogę go użyć jak multi-filter: Przykład filtra Multi

Zrobiłem to rozwiązanie piękna:

Filtr.rura.ts

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

@Pipe({
  name: 'filterx',
  pure: false
})
export class FilterPipe implements PipeTransform {
 transform(items: any, filter: any, isAnd: boolean): any {
  let filterx=JSON.parse(JSON.stringify(filter));
  for (var prop in filterx) {
    if (Object.prototype.hasOwnProperty.call(filterx, prop)) {
       if(filterx[prop]=='')
       {
         delete filterx[prop];
       }
    }
 }
if (!items || !filterx) {
  return items;
}

return items.filter(function(obj) {
  return Object.keys(filterx).every(function(c) {
    return obj[c].toLowerCase().indexOf(filterx[c].toLowerCase()) !== -1
  });
  });
  }
}

Komponent.ts

slotFilter:any={start:'',practitionerCodeDisplay:'',practitionerName:''};

Componet.html

             <tr>
                <th class="text-center">  <input type="text" [(ngModel)]="slotFilter.start"></th>
                <th class="text-center"><input type="text" [(ngModel)]="slotFilter.practitionerCodeDisplay"></th>
                <th class="text-left"><input type="text" [(ngModel)]="slotFilter.practitionerName"></th>
                <th></th>
              </tr>


 <tbody *ngFor="let item of practionerRoleList | filterx: slotFilter">...
 0
Author: Richard Aguirre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-20 17:06:57

Jest dynamiczna rura filtracyjna, której używam

Dane źródłowe:

items = [{foo: 'hello world'}, {foo: 'lorem ipsum'}, {foo: 'foo bar'}];

W szablonie można ustawić filtr w dowolnym obiekcie attr:

<li *ngFor="let item of items | filter:{foo:'bar'}">

Rura:

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

  @Pipe({
    name: 'filter',
  })
  export class FilterPipe implements PipeTransform {
    transform(items: any[], filter: Record<string, any>): any {
      if (!items || !filter) {
        return items;
      }

      const key = Object.keys(filter)[0];
      const value = filter[key];

      return items.filter((e) => e[key].indexOf(value) !== -1);
    }
  }

Nie zapomnij zarejestrować rury w app.module.ts deklaracje

 0
Author: BlackSlash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-15 16:02:38