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.
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 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With