¿Cómo puedo filtrar un array con TypeScript en Angular 2?


Ng-2 la herencia de datos padre-hijo ha sido una dificultad para mí.

Lo que parece que podría ser una buena solución práctica de trabajo es filtrar mi matriz total de datos a una matriz que consiste en datos hijos únicos referenciados por un id padre único. En otras palabras: la herencia de datos se convierte en filtrado de datos por un id padre.

En un ejemplo concreto esto puede verse como: filtrar una matriz de libros para mostrar solo los libros con un cierto 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 es nuevo para mí, pero creo que estoy cerca de hacer que las cosas funcionen aquí.

(También sobrescribir el array original books podría ser una opción, luego usar *ngFor="#book of books".)

EDITAR Cada vez más cerca, pero aún dando un error.

//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
Author: Code-MonKy, 2016-05-03

3 answers

Necesitas poner tu código en ngOnInit y usar la palabra clave this:

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

Necesita ngOnInit porque la entrada store no se establecería en el constructor:

NgOnInit se llama justo después de que las propiedades enlazadas a datos de la directiva se hayan comprobado por primera vez, y antes de que se haya comprobado cualquiera de sus hijos. Sólo se invoca una vez cuando la directiva es instanciado.

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

En su código, el filtrado de libros se define directamente en el contenido de la clase...

 113
Author: Thierry Templier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-03 12:00:43

Puede comprobar un ejemplo en Plunker aquí plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}
 8
Author: yaircarreno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-27 19:51:03

Para filtrar una matriz independientemente del tipo de propiedad (es decir, para todos los tipos de propiedad), podemos crear una tubería de filtro personalizada

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>

No olvide importar la tubería en el módulo de la aplicación

Es posible que necesitemos personalizar la lógica para archivar con fechas.

 0
Author: alchi baucha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-06 02:24:53