8

I have an array of values var_all with a few numeric variables which may or may not be available.

I am using the following code to create a set of boxes displaying the values. The boxes does not change:

<div id="box1">My variable one: {{var_all?.var_one}} </div>
<div id="box2">My variable two: {{var_all?.var_two}} </div>
<div id="box3">My variable three: {{var_all?.var_three}} </div>

When the element is not available, the box is not filled.

I would like in that case to display a zero value instead of nothing.

Is there a way to do it using pipe? Or is it better to use a js function to create an element filled with a zero.

2

2 Answers 2

16

You really don't need a pipe

this is more flexible, and you can easily replace the "0" with whatever else

{{var_all?.var_one || "0"}}

For every one of this null checking, you don't want to instantiate a pipe and run a function for it.

4
  • The only context in which this might not be the best option is if you might want to change the alternate value consistently across your entire application later - in that case, it'd be better to not have it hard coded in all your templates. For the majority of cases though, this is the way to go!
    – Joe Clay
    May 19, 2017 at 14:31
  • @JoeClay I disagree, you can easily provide a variable instead of hardcoding `"0"'
    – Milad
    May 19, 2017 at 14:32
  • Thanks, that's proven to be the simplest solution.
    – YCR
    May 19, 2017 at 14:33
  • @Milad no. Because if you replace "0" by something else, you suddenly find, that all your zeros aren't shown as zeros anymore.
    – UniversE
    Jan 14, 2022 at 16:37
5

Like Joe Clay said in the comment its a super simple pipe. Here is an example of one.

By the way you should definitely read up on how to write pipes and practice writing them. They are really easy once you get a hang of it and very useful.

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

@Pipe({name: 'noNull'})
export class NoNullPipe implements PipeTransform {

  constructor() {}

  transform(num: number | null): number {
    return num ? num : 0;
  }
}
2
  • thanks, I begin with pipe, and it's proven to be a very useful way to deal with minor issues.
    – YCR
    May 19, 2017 at 14:35
  • 1
    No problem. Definitely use the correct tool for the job and in this case the || operator is perfect. But I hope you find other uses for pipes, you can easily alter this one to fit your needs.
    – mikias
    May 19, 2017 at 14:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.