Samy Sammour
Samy Sammour

Reputation: 2465

Dynamic pipe in ngFor Angular2

I am programming an Angular4 application. I have an array contains values and pipe type. (regions, language or number)

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

and I want to make an ngFor so I can display the value and apply the correct pipe: (something like that)

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

I tried to build a class:

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

and I inject an object of the pipe to the class. but it did not work.

is there such a way to do that? or another idea?

P.S. the reason while I am doing that is that I have a huge list of configurations and each one of them has a different pipe type, so hard coded will be kind of hard.

thank you

Upvotes: 4

Views: 3869

Answers (2)

Nima Hakimi
Nima Hakimi

Reputation: 1392

I'd suggest having a main pipe that decides what pipe to apply based on the value:

Main pipe:

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

and in transform function:

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

you also could pass another pipe as an option to your main pipe:

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

Upvotes: 5

Rahul Cv
Rahul Cv

Reputation: 725

Sample Pipe implementation is given below please refer

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


}

in HTML

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

Upvotes: -1

Related Questions