programing

Angular 2에서 TypeScript를 사용하여 어레이를 필터링하려면 어떻게 해야 합니까?

css3 2023. 3. 1. 11:22

Angular 2에서 TypeScript를 사용하여 어레이를 필터링하려면 어떻게 해야 합니까?

ng-2 부모-자녀 데이터 상속은 나에게 어려운 일이었다.

실용적으로 사용할 수 있는 훌륭한 솔루션이라고 생각되는 것은 단일 부모 ID에 의해 참조되는 자녀 데이터만으로 구성된 어레이로 데이터 전체의 배열을 필터링하는 것입니다.즉, 데이터 상속은 하나의 부모 ID에 의한 데이터 필터링이 됩니다.

구체적인 예에서 이것은 다음과 같이 보일 수 있습니다: 특정한 책이 있는 책만 표시되도록 책 배열을 필터링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는 생소하지만, 여기서의 조작은 거의 끝난 것 같습니다.

(또, 원래의 서적 어레이를 덮어쓰는 것도 옵션입니다만,*ngFor="#book of books".)

편집 가까워졌지만 여전히 오류가 발생합니다.

//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

코드를 입력해 주세요.ngOnInit를 사용합니다.this키워드:

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

당신은 필요하다ngOnInit입력이store생성자로 설정되지 않습니다.

ngOnInit은 디렉티브의 데이터 바인딩 속성이 처음 체크된 직후와 그 자식 중 하나가 체크되기 전에 호출됩니다.디렉티브가 인스턴스화될 때 한 번만 호출됩니다.

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

코드에서 도서 필터링은 클래스 콘텐츠에 직접 정의됩니다.

이쪽에 있는 Plunker 예제 필터에서 예를 확인할 수 있습니다.

filter() {

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

속성 유형(즉, 모든 속성 유형에 대해)에 관계없이 배열을 필터링하려면 사용자 지정 필터 파이프를 생성할 수 있습니다.

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>

앱 모듈의 파이프를 가져오는 것을 잊지 마십시오.

로직을 커스터마이즈하여 날짜를 파일링해야 할 수도 있습니다.

언급URL : https://stackoverflow.com/questions/37003551/how-do-i-filter-an-array-with-typescript-in-angular-2