为什么过滤器不适用于角度2?

时间:2016-09-12 04:17:57

标签: angularjs angular angular2-routing

我正在尝试使用pipe或过滤Aangular 2.我收到此错误:

zone.js@0.6.17?main=browser:484 Unhandled Promise rejection: Template parse errors:
The pipe 'search' could not be found ("<div>
                <ul>
                 <li [ERROR ->]*ngFor="let tt of todoService.todo| search">
                <row-item [t]='tt'></row-item>
         "): TodoList@2:21 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors:
The pipe 'search' could not be found ("<div>

这是我的代码: http://plnkr.co/edit/WXgdKF2gx9Kpj7eqmDJv?p=preview

todo-search.ts

import {Pipe, PipeTransform} from "@angular/core";
@Pipe({
name:'search'
})

export class TodoSearch  implements PipeTransform{
transform(value){
  return value.filter((i) =>i.title.startsWith('s'));
}
}

我正在使用像这样的过滤器

<li *ngFor="let tt of todoService.todo| search">

1 个答案:

答案 0 :(得分:2)

您需要将管道添加到声明

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent,Todo,TodoList,TodoRow,TodoSearch],
  bootstrap:    [ AppComponent ]
})

export class AppModule { } 

您还应该使管道对null值安全:

export class TodoSearch  implements PipeTransform{
  transform(value){
    if(!value) {
      return;
    }
    return value.filter((i) =>i.title.startsWith('s'));
  }
}

Plunker example