【问题标题】:Dynamic pipe in ngFor Angular2ngFor Angular2中的动态管道
【发布时间】:2017-12-18 13:09:04
【问题描述】:

我正在编写一个 Angular4 应用程序。我有一个包含值和管道类型的数组。 (地区、语言或数字)

const values = [
   { value: 'us', pipe: 'regions'},
   { value: 'en', pipe: 'language'},
   { value: '100', pipe: 'number'},
.....
];

我想创建一个 ngFor,这样我就可以显示值并应用正确的管道:(类似的东西)

<li *ngFor="let item of values"> {{item.value | item.pipe}} </li>

我尝试建立一个类:

export class FacetConfiguration {
  value: string;
  pipe: Pipe;
}

然后我将管道的一个对象注入到类中。但它没有用。

有这样的方法吗?还是其他想法?

附:我这样做的原因是我有一个庞大的配置列表,每个配置都有不同的管道类型,所以硬编码会有点困难。

谢谢

【问题讨论】:

    标签: angular typescript pipe


    【解决方案1】:

    我建议有一个主管道,根据值决定应用哪个管道:

    主管:

    const values = [
       { value: 'us', pipe: new RegionPipe},
       { value: 'en', pipe: new LanguagePipe},
       { value: '100', pipe: new NumberPipe},
    .....
    ];
    

    在变换函数中:

    trasform(value): any {
       for(let val of values) {
          if(val.value === value) {
              return val.pipe.transform(value);
          }
       }
       return '';
    }
    

    您也可以将另一个管道作为选项传递给您的主管道:

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>{{'some text'| main: test}}</h2>
        </div>
      `,
    })
    export class App {
      name: string;
      test = new TestPipe;
      constructor() {
    
      }
    }
    
    @Pipe({name: 'main'})
    export class MainPipe implements PipeTransform {
      transform(value: any, p: any): any {
        return p.transform(value);
      }
    }
    
    @Pipe({name: 'test'})
    export class TestPipe implements PipeTransform {
      transform(value: any): any {
        return 'test';
      }
    }
    

    【讨论】:

    • 我喜欢。这就是我要找的。但问题是:我可以将管道作为变量发送到主管道,这样我就不必添加额外的外观了吗?比如:trasform(value: string, pipe: Pipe): any { pipe.transform(value);}
    • 你可以看看这个plnkr.co/edit/xjMKVOL1UpfTzD0OpHe3
    【解决方案2】:

    示例管道实现如下,请参考

    import { Pipe, PipeTransform } from '@angular/core';
    
    import { IProduct } from '../products/product';
    @Pipe({
    
      name:'productFilter'
    })
    export class ProductFilterPipe implements PipeTransform{
    
      transform(value: IProduct[], filterBy: string): IProduct[] {
          filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
          return filterBy ? value.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
      }
    
    
    }
    

    在 HTML 中

      <tr *ngFor='let product of products|productFilter:listFilter'>
    

    【讨论】:

    • 这与我的问题相去甚远。我在问一种注入管道的方法,而不是过滤列表的方法。不过还是谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 2017-08-25
    • 2018-03-09
    • 1970-01-01
    • 2016-12-27
    • 2017-05-15
    相关资源
    最近更新 更多