big_OS
big_OS

Reputation: 441

How to use a pipe from variable in html? Angular 9

I'm passing the whole pipe as one of the parameters and I have a hard time using it.
The object format is like the following:

{
    column: 'productExpirationDate', 
    caption: 'Product expiration date', 
    pipe: 'date: \"' + PIPE_DATE_FORMAT + '\"' 
},

While PIPE_DATE_FORMAT holds 'yyyy-MM-dd' the output format should be 'date: "yyyy-MM-dd"'
and if I try to use it in html file like

<span *ngIf="element.pipe">{{ row[element.column] | element.pipe }}</span>

it yells with

Parser Error: Unexpected token '.' ...

I've found Angular - pass pipe as variable post, but I can't figure out how do I make this work in my case. Moreover, get method used in that answear is deprecated which only adds more confusion.

How am I able to use that pipe from variable?

Upvotes: 3

Views: 5327

Answers (3)

Minal Shah
Minal Shah

Reputation: 1486

here you are using the pipe in not so correct manner. First of all your pipe file should have the code as shown below:

@Pipe({
    name: 'customDate'
})
export class CustomDateFormat extends DatePipe implements PipeTransform {
    transform(value: any, args?: string): any {
        let formatter;
        switch (args) {
            case 'PIPE_DATE_FORMAT ':
                {
                    formatter = super.transform(value, 'yyyy-MM-dd');
                    break;
                }
        
                
            default:
                {
                    formatter = super.transform(value, 'dd/mm');
                    break;
                }
        }
        return formatter;
    }
}

And your variable should have such values:

{
  column: 'productExpirationDate', 
  caption: 'Product expiration date', 
  pipe: 'customDate: PIPE_DATE_FORMAT ' 
},

and your html should be replace by:

<span *ngIf="element.pipe">{{ row[element.column] | element.pipe }}</span>

Upvotes: 2

Marcell Kiss
Marcell Kiss

Reputation: 556

What about a custom pipe? You could implement this parametric logic right there in your pipe and your html would look something like this:

<span *ngIf="element.pipe">{{ row[element.column] | myCustomPipe: element.customPipeParams }}</span>

All you should do is implementing myCustomPipe properly, where you can of course reuse the existing angular pipes, eg. the date pipe.

Upvotes: 2

profanis
profanis

Reputation: 2751

You can have the date format in a variable and use this directly in your template

Like the following:

const PIPE_DATE_FORMAT = 'yyyy-MM-dd'

{
    column: 'productExpirationDate', 
    caption: 'Product expiration date', 
},
<span >{{ row[element.column] | date:PIPE_DATE_FORMAT }}</span>

Upvotes: 0

Related Questions