本文介绍了Angular 2中的动态管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个组件,您可以在其中传递应该用于该组件内部列表的管道。通过测试和四处寻找答案,我发现唯一的解决方案似乎是创建以下内容:

I'm trying to create a component where you can pass which pipe that should be used for a list inside the component. From what I could find by testing and looking around for answers the only solution appears to create something like:

<my-component myFilter="sortByProperty"></my-component>

我的组件模板:

<li *ngFor="#item of list | getPipe:myFilter"></li>

然后将 myFilter 映射到正确的管道逻辑并运行它,但这似乎有点脏而且不是最佳的。

Which then maps myFilter to the correct pipe logic and runs it, but this seems a bit dirty and not optimal.

我认为自Angular 1以来,他们将为该问题提供更好的解决方案。在这种情况下,您也可以按照以下方式做一些事情。

I thought they would have come up with a better solution to this problem since Angular 1 where you would also do something along these lines.

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

Is there not a better way to do this in Angular 2?

推荐答案

以borislemke的答案为基础,这是一个不需要 eval()的解决方案,而且我觉得很干净:

Building on borislemke's answer, here's a solution which does not need eval() and which I find rather clean:

dynamic.pipe.ts :

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);
        }
    }
}

app.module.ts:

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 { }

app.component.ts:

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 = [];
}

这篇关于Angular 2中的动态管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:48