Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2: use pipe to replace undefined value by zero

Tags:

angular

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.

like image 421
YCR Avatar asked May 19 '17 14:05

YCR


2 Answers

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.

like image 200
Milad Avatar answered Oct 10 '22 14:10

Milad


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;
  }
}
like image 35
mikias Avatar answered Oct 10 '22 15:10

mikias