When I'm trying to do this:
dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}"
It gives me this error:
browser_adapter.ts:82 ORIGINAL EXCEPTION: TypeError: self.context.isNaN is not a function
How can I check if my object is a not number in Angular2 expression?
You can expose the function as a property of the class:
class MyComponent {
isNaN: Function = Number.isNaN;
}
<div>dividerColor="{{isNaN(+price) ? 'warn' : 'primary'}}"</div>
Other answers suggests to create a component function to check whether the value is NaN like:
*ngIf="myCustomIsNaN(value)"
This approach is, as far as I know, a problem in Angular because you're calling a function to check the value. So the change detector will continue to call that function to check if the value returned changed. If you put a console.log in that function you'll see it is called 1 to 10 times a second thus re rendering the template.
I think the only good way to do this is to use a custom Pipe.
Consider the following template code:
<div *ngIf="value | isNan"> ... </div>
In this case the change detector trigger a re rendering only if value
changes. And then it evaluates the ngIf
statement and re renders the template accordingly.
Less calls, less renderings, less cpu utilization, more performance. :)
For elegance in templates I created two pipes to check NaNs: isNaN
and isNotNaN
import { Pipe, PipeTransform } from '@angular/core';
/**
* Pipe to return true if the number is NaN
*/
@Pipe({
name: 'isNaN'
})
export class IsNaNPipe implements PipeTransform {
transform(item: number): boolean {
return isNaN(item);
}
}
/**
* Pipe to return true if the number is NOT NaN
*/
@Pipe({
name: 'isNotNaN'
})
export class IsNotNaNPipe implements PipeTransform {
transform(item: number): boolean {
return !isNaN(item);
}
}
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