Smokey Dawson
Smokey Dawson

Reputation: 9240

Use Angular Pipe within shorthand if statement

How can I use a custom pipe within a shorthand if statement??

This is the code I am trying to use

<h1>Total Value {{data ? totalValue | moneyFormat : '$0'}}

and this is the error I am getting

Template parse errors:
Parser Error: Conditional expression data ? totalValue | moneyFormat : null requires all 3 expressions at the end of the expression

So basically I have set up a pipe that formats money, this is my pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'moneyFormat'})
export class MoneyFormatPipe implements PipeTransform {
    transform(value: number) {
        const formatter = new Intl.NumberFormat('en-US', {
          style: 'currency',
          currency: 'USD'
        });
        let formattedValue = formatter.format(value);
        formattedValue = formattedValue.slice(0, -3);
        return formattedValue;
    }
}

Now I know this works since I have used this else where in scenarios like

<p>This is your dollar amount {{dollarAmount | formatMoney}}

Am I missing something? Am I doing this wrong?

Keep in mind what I have done is an example for simplicity sake and not the true functionality of the conditional statement. I am fully aware I could return $0 using the pipe.

Upvotes: 0

Views: 643

Answers (2)

yurzui
yurzui

Reputation: 214305

I think you need to wrap some part in parenthesis:

{{data ? (totalValue | moneyFormat) : '$0'}

Upvotes: 2

Austin T French
Austin T French

Reputation: 5140

I'd try a more explicit format for what it should do:

{{(data ? totalValue : '$0') | moneyFormat }}

which should evaluate roughly to :

if (data) {totalValue | moneyFormat;} else { '$0' | moneyFormat }

Upvotes: 0

Related Questions