2017-10-05 2 views
0

각도 2 파이프를 학습 중이며 문제가 발생했습니다. 하나의 입력을 선택하면 카드 목록을 표시하는 * ngFor에서 데이터를 필터링해야하는 자동 완료 상자가 있습니다. 현재 자동 완성 작업을 시작할 때 실제 카테고리를 선택하면 ngFor의 카드 목록이 필터링되지 않습니다. 내가 뭘 놓치고 있니? 여기 각도 2 자동 완성 필터 * 데이터 데이터

<form class="example-form"> 
    <md-form-field class="example-full-width"> 
    <input type="text" placeholder="Select a sport" aria-label="Number" mdInput 
    [formControl]="myControl" [mdAutocomplete]="auto"> 
    <md-autocomplete #auto="mdAutocomplete"> 
    <md-option *ngFor="let option of filteredOptions | matchesSport:option | 
    async" [value]="option"> 
     {{ option }} 
    </md-option> 
    </md-autocomplete> 
</md-form-field> 
</form> 

는 MD-카드의 목록이 표시 ngFor 내 *입니다 :

감사

그래서 여기

내 자동 완성 여기

<md-list>  
    <md-list-item *ngFor="let g of games; let i = index | matchesSport:option" (click)="onSelect(g)" [class.active]="i == selectedRow"> 
    <md-card tabindex="-1"> 
     <md-card-content> 
     <p md-line> {{g.Sport}}<span><i class="material-icons">accessibility</i></span> </p> 
     </md-card-content> 
     <md-card-actions> 
     <button md-button md-raised-button>LIKE</button> 
     <button md-button md-raised-button>SHARE</button> 
     </md-card-actions> 
    </md-card> 
    </md-list-item> 
</md-list> 

그리고 나의 파이프

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

@Pipe({ 
    name:'matchesSport' 
}) 

export class MatchesSportPipe implements PipeTransform { 
    transform(items: any, category: string): Array<any> {    
    return items.filter(item => item.Sport === category); 
    } 
} 

여기

import { Component, OnInit } from '@angular/core'; 
import { Game } from './models/game.model'; 
import { GameService } from './services/game-service'; 
import { FormControl } from '@angular/forms'; 
import { Observable } from 'rxjs/Observable';  
import 'rxjs/add/operator/startWith'; 
import 'rxjs/add/operator/map'; 

export class AppComponent implements OnInit { 
    title = 'app'; 
    games: any[] = [ ]; 
    statusMessage: string = "Loading games..."; 
    selectedRow: Object; 
    setClickedRow: Function; 
    selectedGame: Game; 
    myControl: FormControl = new FormControl(); 

    options = [ 
    'Football', 
    'Basketball', 
    'Baseball', 
    'Lacrosse', 
    'Volleyball' 
    ]; 

    filteredOptions: Observable<string[]>; 

    constructor(private _gameService: GameService) { 
    this.filteredOptions = this.myControl.valueChanges 
    .startWith(null) 
    .map(val => val ? this.filter(val) : this.options.slice()); 
    } 
    filter(val: string): string[] { 
    return this.options.filter(option => 
    option.toLowerCase().indexOf(val.toLowerCase()) === 0); 
    } 

    onSelect(game: Game): void { 
    this.selectedGame = game; 
    } 


    ngOnInit() { 
     return this._gameService.getGames() 
     .subscribe((gameData) => this.games = gameData, 
     (error) => { 
     this.statusMessage = " something broke" 
    }); 

    } 
} 
+0

가 나는 작업 바이올린으로 업데이트 한 대답을 참조하십시오. – Fetrarij

답변

1

첫째, 지수는 파이프 후에해야한다 :

<md-list-item *ngFor="let g of games | matchesSport:option; let i = index "> 
    ... 
</md-list-item> 

그리고, 당신이 파이프에 정의되지 option를 사용하여 내 컨트롤러입니다. 당신은 자동 완성에서 choosed 할 값을 취득하고 (여기 option)를이에게 파이프 인수를 넣어해야합니다

사용할 수 : optionSelected 이벤트를 매트 자동 완성

<mat-autocomplete #auto="matAutocomplete" (optionSelected)="optionSelected($event)" name="myname"> 
    <mat-option *ngFor="let option of options" [value]="option"> 
... 
    </mat-option> 
</mat-autocomplete> 

과 구성 요소 :

option: string; // <-- use it now 
// ... 
optionSelected(e) { 
    this.option = e.option.value; 
} 

그런 오류에 대한 :

error of : ERROR TypeError: Cannot read property 'filter' of undefined at MatchesSportPipe.webpackJsonp.../../../../../src/app/customP‌​ipe.ts.MatchesSportP‌​ipe.transform (customPipe.ts:9)

이제 필요 항목을 정의하기 전에 항목이 정의되지 않은 경우 파이프를 체크인하고 항목을 필터링하기 전에 범주가 정의되지 않은 경우 확인하십시오.

export class MatchesSportPipe implements PipeTransform { 
    transform(items: any[], category: string): Array<any> { 
    if (!items) return []; 
    if (!category) return items;   
    return items.filter(item => item.Sport === category); 
    } 

전체 동작을

는 작업 plunker 재개 : https://embed.plnkr.co/4NDIy84YFW7OZkVPJZo5/

+0

오류 : ERROR TypeError : MatchesSportPipe.webpackJsonp .../../../../src/app/customPipe.ts.MatchesSportPipe.transform (customPipe.)에서 정의되지 않은 속성 'filter'을 읽을 수 없습니다. ts : 9) –

+0

그래서이 작업을 수행했습니다. 내보내기 클래스 MatchesSportPipe는 PipeTransform { transform (items : any [], category : string) : Array { return items.filter (item => item.Sport === category) ; } }와 같은 오류 –

+0

@ TroyBryant 또는 데이터가 정의 된 경우에도 파이프가 작동하도록 체크인 할 수 있습니다. – Fetrarij