过滤@Pipe错误中的数据

时间:2017-02-14 12:21:54

标签: angular typescript filtering grouping

我正在尝试过滤数据并在htmltable中呈现它。 在我的代码下面: 在module.ts

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。我知道还有其他方法,但这个我更喜欢。但我得到例外。

  

未处理的Promise拒绝:模板解析错误:管道'过滤器'   无法找到(“                                                             ] * ngFor =“let data2 of(model.Register10Data | filter:'sectionGroup':data1.id); let dataIndex   = index“&gt;”):e @ 68:20;区域:;任务:Promise.then;值:错误:模板分析错误:找不到管道“过滤器”(“                                                             ] * ngFor =“let data2 of(model.Register10Data | filter:'sectionGroup':data1.id); let dataIndex   = index“&gt;”):e @ 68:20

2 个答案:

答案 0 :(得分:0)

尝试在属性+过滤器周围添加括号?

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

答案 1 :(得分: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 { }