Angular 2中的动态管道

Chr*_*odz 14 angular2-pipe angular

我正在尝试创建一个组件,您可以在其中传递应该用于组件内的列表的管道.从我通过测试和寻找答案找到的,唯一的解决方案似乎创建类似于:

<my-component myFilter="sortByProperty"></my-component>
Run Code Online (Sandbox Code Playgroud)

my-component 模板:

<li *ngFor="#item of list | getPipe:myFilter"></li>
Run Code Online (Sandbox Code Playgroud)

然后映射myFilter到正确的管道逻辑并运行它,但这看起来有点脏,不是最佳的.

我认为他们会提出一个更好的解决方案来解决这个问题,因为Angular 1你也会沿着这些方向做一些事情.

在Angular 2中没有更好的方法吗?

bal*_*alu 31

基于borislemke的回答,这里有一个不需要的解决方案eval(),我发现它很干净:

dynamic.pipe.ts:

import {
    Injector,
    Pipe,
    PipeTransform
} from '@angular/core';


@Pipe({
  name: 'dynamicPipe'
})
export class DynamicPipe implements PipeTransform {

    public constructor(private injector: Injector) {
    }

    transform(value: any, pipeToken: any, pipeArgs: any[]): any {
        if (!pipeToken) {
            return value;
        }
        else {
            let pipe = this.injector.get(pipeToken);
            return pipe.transform(value, ...pipeArgs);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

app.module.ts:

// …
import { DynamicPipe } from './dynamic.pipe';

@NgModule({
  declarations: [
    // …
    DynamicPipe,
  ],
  imports: [
    // …
  ],
  providers: [
    // list all pipes you would like to use
    PercentPipe,
    ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { PercentPipe } from '@angular/common';

@Component({
  selector: 'app-root',
  template: `
    The following should be a percentage: 
    {{ myPercentage | dynamicPipe: myPipe:myPipeArgs }}
    `,
  providers: []
})

export class AppComponent implements OnInit {
  myPercentage = 0.5;
  myPipe = PercentPipe;
  myPipeArgs = [];
}
Run Code Online (Sandbox Code Playgroud)

  • 我不能让它工作。我收到以下错误 `Error: StaticInjectorError(AppModule)[date]: StaticInjectorError(Platform: core)[date]: NullInjectorError: No provider for date!` (3认同)