Angular 2中的动态管道

时间:2016-04-12 06:17:26

标签: angular angular2-pipe

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

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

my-component模板:

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

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

我认为他们会想出更好的解决方案来解决这个问题,因为Angular 1你也可以在这些方面做点什么。

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

6 个答案:

答案 0 :(得分:26)

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

答案 1 :(得分:3)

不幸的是我不这么认为。它与angular1中的相同,你有一个函数返回一个你想要的动态管道的字符串。

查看文档,以及它们是如何显示的。

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

intercept()

然后在控制器中:

template: `
   <p>The hero's birthday is {{ birthday | date:format }}</p>
   <button (click)="toggleFormat()">Toggle Format</button>
`
唉,可能会更糟! :)

答案 2 :(得分:3)

我设法得到了一些有用的东西,它有点肮脏和邪恶(带有eval),但它对我有用。在我的例子中,我有一个表组件,每行有不同的数据类型(例如标题,网址,日期,状态)。在我的数据库中,状态被标记为1enabled0disabled。当然,更优选的是向我的用户显示启用/禁用。此外,我的标题列是多语言的,这使得它成为enid作为其关键字的对象。

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

理想情况下,我需要2个不同的管道来转换我的数据以显示给我的应用程序的用户。像translateTitlegetStatus之类的东西会很好。让我们拨打父管道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>

将返回:

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

答案 3 :(得分:3)

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

答案 4 :(得分:0)

在@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;
        }
    }
}

答案 5 :(得分:0)

我通过将管道提供程序发送到组件来处理此问题,并且它运行了transform方法。而且它可以与Angular 9一起使用。演示:https://stackblitz.com/edit/angular-kdqc5e

pipe-in​​jector.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);
      }
    }

app-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 { }
相关问题