0

let suppose I am accessing and showing data in html like this

{{whole_data?.age_range ? whole_data?.age_range : '-'}}

Now problem here is, if in case whole_data?.age_range is evaluated to 0 or null it will show - always, except expression value is non zero or not null,

My question is

  1. why so (is zero is treated as false in this case) ?

  2. what is the alternate for the same ?

PS:- I don't want to use condition especially for checking value is zero or not, because this syntax I am using 1000 of times in my code

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215

1 Answers1

3

You can make your template expression shorter, but it will have the same outcome:

{{whole_data?.age_range || '-'}}

There is no other way. 0 is always evaluated to false. You should use a pipe to prevent duplicate code:

@Pipe({
    name: "dashNumber"
})
export class DashNumber implements PipeTransform {

    transform(value: number): number {
        value = parseFloat(value);
        return isNaN(value) ? '-' : value;
    }

}

usage:

{{whole_data?.age_range | dashNumber}}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149