ngFor Angular2中的动态管道

时间:2017-07-13 16:03:43

标签: angular typescript pipe

我正在编写一个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;
}

我将管道的一个对象注入到类中。但它不起作用。

有这样的方法吗?或另一个想法?

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

谢谢

2 个答案:

答案 0 :(得分:4)

我建议使用一个主管道根据值确定要应用的管道:

主管道:

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

答案 1 :(得分:-1)

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

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'>