Angular 2 中的动态管道

Dynamic pipe in Angular 2

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

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

my-component 模板:

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

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

我认为自 Angular1 以来,他们会想出更好的解决方案来解决这个问题,您也可以按照这些思路做一些事情。

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

很遗憾,我不这么认为。它与 angular1 相同,你有一个函数 return 一个字符串,用于你想要的动态管道。

查看文档,他们也正是这样显示的。

https://angular.io/docs/ts/latest/guide/pipes.html

template: `
   <p>The hero's birthday is {{ birthday | date:format }}</p>
   <button (click)="toggleFormat()">Toggle Format</button>
`

然后在控制器中:

get format()   { return this.toggle ? 'shortDate' : 'fullDate'}

唉,情况可能更糟! :)

我设法让一些东西工作,它有点肮脏和邪恶(使用 eval),但它对我有用。在我的例子中,我有一个 table 组件,每一行都有不同的数据类型(例如标题、url、日期、状态)。在我的数据库中,状态标记为 1 作为 enabled0 作为 disabled。当然,向我的用户显示 enabled/disabled 更可取。此外,我的标题栏是多语言的,这使它成为一个 object,其中 enid 是关键。

// Example row object:
title: {
    "en": "Some title in English",
    "id": "Some title in Indonesian"
},
status: 1 // either 1 or 0

理想情况下,我需要 2 个不同的管道来转换我的数据以显示给我的应用程序用户。 translateTitlegetStatus 这样的东西就可以了。我们称 parent 的管道为 dynamicPipe.

/// some-view.html
{{ title | dynamicPipe:'translateTitle' }}
{{ status | dynamicPipe:'getStatus' }}


/// dynamic.pipe.ts
//...import Pipe and PipeTransform

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

    transform(value:string, modifier:string) {
        if (!modifier) return value;
        return eval('this.' + modifier + '(' + value + ')')
    }

    getStatus(value:string|number):string {
        return value ? 'enabled' : 'disabled'
    }

    translateTitle(value:TitleObject):string {
        // defaultSystemLanguage is set to English by default
        return value[defaultSystemLanguage]
    }
}

我可能会非常讨厌使用 eval。希望对您有所帮助!

更新:在您可能需要的时候

posts = {
    content: [
        {
            title:
                {
                    en: "Some post title in English",
                    es: "Some post title in Spanish"
                },
            url: "a-beautiful-post",
            created_at: "2016-05-15 12:21:38",
            status: 1
        },
        {
            title:
                {
                    en: "Some post title in English 2",
                    es: "Some post title in Spanish 2"
                },
            url: "a-beautiful-post-2",
            created_at: "2016-05-13 17:53:08",
            status: 0
        }
    ],
    pipes: ['translateTitle', null, 'humanizeDate', 'getStatus']
}

<table>
    <tr *ngFor="let row in posts">
        <td *ngFor="let column in row; let i = index">{{ column | dynamicPipe:pipes[i] }}</td>
    </tr>
</table>

会 return:

| title          | url            | date           | status         |
| Some post t...   a-beautiful...   an hour ago      enabled
| Some post ...2   a-beautifu...2   2 days ago       disabled

解决此问题的最简单方法是不使用 HTML 模板中的管道,而是将管道注入组件的构造函数(使用 DI),然后按功能应用转换。这对于 Observable 地图或类似的 rxjs 流非常有效。

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

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:

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

在@Balu 的基础上回答这个我必须做的事情才能让它与 Angular 9

一起工作
import { Injector, Pipe, PipeTransform } from '@angular/core';
import { PercentPipe, CurrencyPipe, DecimalPipe } from '@angular/common';

@Pipe({
    name: 'dynamicPipe'
})

export class DynamicPipe implements PipeTransform {

    public constructor(private injector: Injector, private percentPipe: PercentPipe) {
    }

    transform(value: any, pipeToken: any, pipeArgs: any[]): any {

        const MAP = { 'currency': CurrencyPipe, 'decimal': DecimalPipe, 'percent': PercentPipe }

        if (pipeToken && MAP.hasOwnProperty(pipeToken)) {
            var pipeClass = MAP[pipeToken];
            var pipe = this.injector.get(pipeClass);
            if (Array.isArray(pipeArgs)) {
                return pipe.transform(value, ...pipeArgs);
            } else {
                return pipe.transform(value, pipeArgs);
            }
        }
        else {
            return value;
        }
    }
}

我通过将管道提供程序发送到组件并运行转换方法来处理这个问题。它适用于 Angular 9. 我希望它能帮助别人!演示:https://stackblitz.com/edit/angular-kdqc5e

管道-injector.component.ts:

import { Component, OnInit, Input, PipeTransform } from '@angular/core';
    @Component({
      selector: 'pipe-injector',
      template: `
        Should inject my pipe provider 
        {{ getText() }}
        `,
      providers: []
    })


    export class PipeInjectorComponent {
      @Input() pipeProvider: PipeTransform;
      @Input() pipeArgs: Array<any>;
      @Input() textToFormat: string;

      getText() {
        return this.pipeProvider.transform(this.textToFormat, ...this.pipeArgs);
      }
    }

应用-component.ts:

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

@Component({
  selector: 'app-root',
  template: `
    <pipe-injector [pipeProvider]="pipeProvider" [pipeArgs]="pipeArgs" textToFormat='05-15-2020'> 
    </pipe-injector>
    `,
  providers: []
})

export class AppComponent implements OnInit {
  pipeArgs = ['dd/MM/yyyy'];
  constructor(public pipeProvider: DatePipe) {}
}

app.module.ts:

import { DatePipe } from '@angular/common';
import { PipeInjectorComponent } from './pipe-injector.component';

@NgModule({
  declarations: [

    PipeInjectorComponent,
  ],
  imports: [
  ],
  providers: [
    DatePipe,
    ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我在@balu 的

中添加了一些类型
import { Pipe, PipeTransform } from '@angular/core';

export type OmitFirstArg<T extends unknown[]> = T extends [unknown, ...infer U] ? U : never;

@Pipe({
  name: 'dynamicPipe',
  pure: true
})
export class DynamicPipe<P extends PipeTransform> implements PipeTransform {
  public transform(
    value: Parameters<P['transform']>[1],
    pipeTransform: P,
    pipeArgs?: OmitFirstArg<Parameters<P['transform']>>): ReturnType<P['transform']> | unknown {
    if (!('transform' in pipeTransform)) {
      return value;
    }
    return pipeTransform.transform(value, ...(pipeArgs || []));
  }
}