2017-02-14 30 views
1

我試圖過濾數據並將其呈現在htmltable中。 下面我的代碼: 在module.ts在@Pipe中過濾數據錯誤

import Register10Pipe = require("./register10/register10.pipe"); 
@NgModule({ 
    declarations: [ 
     Register10Pipe.FilterPipe 
    ]) 

在my.pipe.ts

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

@Pipe({ 
    name: 'sectionGroup' 
}) 

export class FilterPipe implements PipeTransform { 
    transform(items: any[], field: number, value: number): any[] { 
     if (!items) return []; 
     return items.filter(it => (+it[field]) === (+value)); 
    } 
} 

在my.component.ts

import { FilterPipe } from './register10.pipe'; 
export class MyComponent implements OnInit { 
    filter: FilterPipe; 
...... 

HTML,其中的數據必須呈現

<ng-container *ngFor='let data1 of sectionList'> 
     <tr> 
      <td colspan="7"> 
       {{data1.name}} 
       <button (click)="ArrRow($event)" style="float: right" id="{{data1.id}}">+</button> 
      </td> 
     </tr> 
     <tr *ngFor="let data2 of (model.Register10Data | filter:'sectionGroup':data1.id); let dataIndex = index"> 
      <td> 
       {{dataIndex}} 
      </td> 
     </tr> 
    </ng-container> 

sectionList它是像myObj這樣的對象數組{number:id,string:name} 我從此數組中獲取id並嘗試過濾從服務器接收的數據。正如我所理解的在角度可以使用@Pipe。我知道還有其他的方法,但是我更喜歡這個。但我得到例外。

Unhandled Promise rejection: Template parse errors: The pipe 'filter' could not be found (" ]*ngFor="let data2 of (model.Register10Data | filter:'sectionGroup':data1.id); let dataIndex = index">"): [email protected]:20 ; Zone: ; Task: Promise.then ; Value: Error: Template parse errors: The pipe 'filter' could not be found (" ]*ngFor="let data2 of (model.Register10Data | filter:'sectionGroup':data1.id); let dataIndex = index">"): [email protected]:20

+0

您的自定義管什麼管中的'+'在做什麼? –

+0

@Christopher。它將值轉換爲一個數字(我假設) – AngularChef

+0

ok - 你在兩個嵌套的for循環中聲明瞭'data',這可能不會幫助調試的提示 –

回答

0

嘗試在屬性+過濾器周圍添加括號?

<tr *ngFor="let data of (model.Register10Data | filter:'sectionGroup':'cSectionId'); let dataIndex = index"> 
</tr> 
0

試試這個

<ng-container *ngFor='let data1 of sectionList'> 
    <tr> 
     <td colspan="7" >{{data1.name}} 
      <button (click)="ArrRow($event)" style="float: right" id="{{data1.id}}" >+</button> 
     </td> 
    </tr> 
    <tr *ngFor="let data2 of (model.Register10Data | filter:'sectionGroup':data1.id); let dataIndex = index"> 
     <td> 
      {{dataIndex}} 
     </td> 
    </tr> 
</ng-container> 

您可以在第二個從第一ngFor訪問值,但只有當你聲明在不同的名字data1data2這裏。

如果您還沒有這樣做的話,包括在app.module.ts

... 
import { FilterPipe } from './filter.pipe'; 

@NgModule({ 
    imports: [ 
    ..., 
    ], 
    declarations: [ 
    ..., 
    FilterPipe 
    ], 
}) 
export class MyModule { } 
+0

現在我得到folow異常:'未處理的承諾拒絕:模板解析錯誤:無法找到管'過濾器'也許我創建@Pipe不正確? – Seva

+0

至少進展,你有沒有在你的'app.modules.ts'聲明中包含管道? –

+0

我mus包括FilterPipe類?如果是的話,它是怎麼做的? – Seva