如何从 Angular 2 中的组件创建和调用管道?

How to create and call a pipe from the component in Angular 2?

我想创建一个我要从组件调用的动态管道。

import {Component, Pipe, PipeTransform} from 'angular2/core';

@Pipe({ name: 'filter', pure: false })
export class filter implements PipeTransform {
  transform(value) {
    this.items1=value;
    this.ticket1 = [];
    if (this.items1.length >0) {
      for (var i = 0; i < this.items1.length; i++) {
        this.ticket1.push(this.items1[i])
      }
    }
  }
}

我想从组件中调用这个管道。

您需要在组件的 pipes 属性中指定它

@Component({
  pipes: [ filter ] 
})
export class MyComponent {
  (...)
}

并在您的模板中使用它:

{{someArray | filter}}
<div *ngFor="someArray | filter">(...)</div>

编辑

如果要在组件class内直接调用管道,需要实例化并调用它的tranform方法:

@Component({
  (...)
})
export class MyComponent {
  constructor() {
    let filterPipe = new filter();
    let arr = [ ... ];
    var fiteredArr = filterPipe.transform(arr);
  }
  (...)
}

您需要注册要在组件中使用的管道:

@Component({
  ...
  pipes: [filter],
  template: `
<div *ngFor="let item of someData | filter">{{item}}</div>
`
  ...})
class SomeComponent {
  someData = [ ... ];
}
@NgModule({
  imports: [CommonModule],
  declarations: [filter]
})
export class MyFilterModule()

要使管道可用,请将模块添加到要使用它的导入中

@NgModule({
  declarations: [AppComponent, SomeComponent],
  imports: [BrowserModule, MyFilterModule]
})
export class AppModuleModule()

如果你想从代码中调用管道

let f = new filter();
f.transform(value, filterArg);

在 rc6 版本中,您需要注册要在模块中使用的管道 -> 声明

@NgModule({
    declarations: [
        AppComponent ,
        filter
    ]....

我只是想补充 答案。 Angular 2+ 包括 Ionic 2+ 都希望在模块中声明管道:

@NgModule({
    declarations: [
        AppComponent ,
        filter
    ]

这也是唯一需要声明管道的地方。模块或组件下不再有管道 属性。

如果您想在不同模块上多次使用管道,我建议您将所有管道聚合到一个模块中(例如,PipesAggrModule),然后将此模块导入到所需模块中。例如:

my-pipe.module.ts

@Pipe({name: 'MyPipe'})
export class MyPipe { ... }

pipes-aggr.module.ts:

@NgModule({
  imports: [
    CommonModule
  ],
  exports: [
    ...
    MyPipe,
    MyPipe2,
    ...
  ],
  declarations: [..., MyPipe, MyPipe2, ...]
})
export class PipesAggrModule {}

然后,要使用您的管道,只需将 PipesAggrModule 导入所需的模块即可。

my.module.ts

@NgModule({
  imports: [
    CommonModule,
    PipesAggrModule
  ],
...
}
export class MyModule {}