Come faccio a filtrare un array con TypeScript in Angular 2?


109

L'ereditarietà dei dati genitore-figlio ng-2 è stata una difficoltà per me.

Quella che sembra che potrebbe essere una soluzione pratica funzionante è filtrare il mio array totale di dati in un array composto solo da dati figlio a cui fa riferimento un unico ID genitore. In altre parole: l'ereditarietà dei dati diventa il filtraggio dei dati in base a un ID genitore.

In un esempio concreto questo può assomigliare a: filtrare un array di libri per mostrare solo i libri con un determinato store_id.

import {Component, Input} from 'angular2/core';

export class Store {
  id: number;
  name: string;
}

export class Book {
  id: number;
  shop_id: number;
  title: string;
}

@Component({
  selector: 'book',
  template:`
    <p>These books should have a label of the shop: {{shop.id}}:</p>

    <p *ngFor="#book of booksByShopID">{{book.title}}</p>
  `
])
export class BookComponent {
  @Input()
  store: Store;

  public books = BOOKS;

  // "Error: books is not defined"
  // ( also doesn't work when books.filter is called like: this.books.filter
  // "Error: Cannot read property 'filter' of undefined" )
  var booksByStoreID = books.filter(book => book.store_id === this.store.id)
}

var BOOKS: Book[] = [
  { 'id': 1, 'store_id': 1, 'name': 'Dichtertje' },
  { 'id': 2, 'store_id': 1, 'name': 'De uitvreter' },
  { 'id': 3, 'store_id': 2, 'name': 'Titaantjes' }
];

TypeScript è nuovo per me, ma penso di essere vicino a far funzionare le cose qui.

(Anche la sovrascrittura dell'array di libri originale potrebbe essere un'opzione, quindi l'utilizzo *ngFor="#book of books".)

EDIT Avvicinandosi, ma dando ancora un errore.

//changes on top:
import {Component, Input, OnInit} from 'angular2/core';

// ..omitted

//changed component:
export class BookComponent implements OnInit {
  @Input() 
  store: Store;

  public books = BOOKS;

  // adding the data in a constructor needed for ngInit
  // "EXCEPTION: No provider for Array!"
  constructor(
    booksByStoreID: Book[];
  ) {}


  ngOnInit() {
    this.booksByStoreID = this.books.filter(
      book => book.store_id === this.store.id);
  }
}

// ..omitted

Risposte:


205

Devi inserire il tuo codice ngOnInite utilizzare la thisparola chiave:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

Hai bisogno ngOnInitperché l'input storenon sarebbe impostato nel costruttore:

ngOnInit viene chiamato subito dopo che le proprietà associate ai dati della direttiva sono state controllate per la prima volta e prima che i suoi figli siano stati controllati. Viene invocato solo una volta quando viene creata un'istanza della direttiva.

( https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html )

Nel tuo codice, il filtro dei libri è definito direttamente nel contenuto della classe ...


Ha senso. Ottengo l'errore "Errore: ngOnInit non è definito" dopo aver aggiunto il tuo pezzo di codice, importato OnInite aggiunto booksByStoreID = Book[];nel componente.
Code-MonKy

Penso che sia piuttosto:booksByStoreID: Book[];
Thierry Templier

Non funziona neanche. Forse dovrei metterlo in un costruttore? Ho provato questo, poi ricevo un errore lamentandomi di]
Code-MonKy

1
Grazie! Il filtraggio funziona completamente :) Tuttavia è sorto un nuovo problema. Quando si fa clic nel componente principale in modo tale da selezionare un altro negozio, il vecchio store_id rimane e l'elenco dei libri rimane lo stesso ...
Code-MonKy

1
Eccellente. complimenti per 200 voti !!!
Amuk Saxena

18

Puoi controllare un esempio in Plunker qui filtri di esempio plunker

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

4

Per filtrare un array indipendentemente dal tipo di proprietà (cioè per tutti i tipi di proprietà), possiamo creare una pipe di filtro personalizzata

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

@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
  transform(itemList: any, searchKeyword: string) {
    if (!itemList)
      return [];
    if (!searchKeyword)
      return itemList;
    let filteredList = [];
    if (itemList.length > 0) {
      searchKeyword = searchKeyword.toLowerCase();
      itemList.forEach(item => {
        //Object.values(item) => gives the list of all the property values of the 'item' object
        let propValueList = Object.values(item);
        for(let i=0;i<propValueList.length;i++)
        {
          if (propValueList[i]) {
            if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
            {
              filteredList.push(item);
              break;
            }
          }
        }
      });
    }
    return filteredList;
  }
}

//Usage

//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>

Non dimenticare di importare la pipe nel modulo dell'app

Potrebbe essere necessario personalizzare la logica per il filer con le date.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.