CounterFlame
CounterFlame

Reputation: 1632

How to use Pipe passed as @Input in HTML template

I made a reusable Component that accepts an array of a certain class. Now I want to pass a Pipe to this Component that will transform each element of that array into the visual representation I want. (This changes depending on the class of the array objects).

Now I don't know how to use this Pipe directly in the template. I managed to get it to work with an extra function that calls the pipe programmatically:

export class SingleCategoryFilterComponent<T> implements OnInit {

  @Input()
  possibleFilterValues: T[];
  @Input()
  displayPipe: PipeTransform;

  constructor() {}

  ngOnInit() {}

  transformValue(value: T) {
    return this.displayPipe.transform(value);
  }

}

and the (partial) template:

<button mat-menu-item *ngFor="let value of possibleFilterValues">
    {{transformValue(value)}}
</button>

But I would prefer to not have to create this transform function, and just be able to do something like:

<button mat-menu-item *ngFor="let value of possibleFilterValues">
    {{value | displayPipe}}
</button>

but that doesn't seem to work, as displayPipe is not registered. Is there a way to use the variable @Input displayPipe in the template?

Upvotes: 5

Views: 3526

Answers (2)

seabass
seabass

Reputation: 1120

<button mat-menu-item *ngFor="let value of possibleFilterValues">
    {{displayPipe.transform(value)}}
</button>

works for me.

It's not the

{{value | displayPipe}}

you were looking for, but it's the shortest solution Ive found.

Upvotes: 0

amal
amal

Reputation: 3170

How about if you use a wrapper pipe that takes care of this for you in the template and you pass in the displayPipe pipe as an argument of the pipe's transform method. Something like below (might need some sort of tweaking to suit your question, but you get the idea)

In template,

<button mat-menu-item *ngFor="let value of possibleFilterValues">
    {{value | wrappingPipe:displayPipe}}
</button>

The wrapper pipe,

@Pipe({
  name: 'wrappingPipe'
})
export class WrappingPipe implements PipeTransform {
  transform(value: any, displayPipe?: PipeTransform): any {
    if(value !== undefined) {
      return displayPipe && displayPipe.transform ? displayPipe.transform(value) : value;
    } else {
      return value;
    }
  }
}

Upvotes: 3

Related Questions