I'm learning Angular2. I have a component with a variable which is an object. I'm iterating over the fields of the object, and acording to the type of data of that position, I need to render a different compoenent. In this case, I want tu render that label
if the typeof
that position is a number
how ever this is not working
<div> <div *ngIf='obj'> <label *ngFor="let key of keys; let i = index"> <label class='key'>{{key}}:</label> <label class='number' *ngIf='typeof obj[key] === "number"'> <!-- label class='number' *ngIf='obj[key] | typeof === "number"' --> {{ obj[key] }} </label> </label> </div> </div>
Any ideas?
I have also created a pipe to get the typeof
which work when I print the value, but not inside the *ngIf
Use double equal to == operator to check equality or better use === to check strict equality. You should use === in Javascript instead.
ngIf expression example and === and == operator is used to compare the strings and returns Boolean value.
The NgIf directive is used when you want to display or remove an element based on a condition. If the condition is false the element the directive is attached to will be removed from the DOM .
The ngIf directive removes or recreates a portion of the DOM tree based on an {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
Globals like window
, typeof
, enums, or static methods are not available within a template. Only members of the component class and typescript language constructs are available.
You can add a helper method to your component like
isNumber(val): boolean { return typeof val === 'number'; }
and use it like
<label class='number' *ngIf='isNumber(obj[key])'>
You can create simple pipe which will receive current item and return item type.
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'typeof' }) export class TypeofPipe implements PipeTransform { transform(value: any): any { console.log("Pipe works ", typeof value); return typeof value; } }
Now you can use typeof
pipe in html like this
*ngIf = (item | typeof) === 'number'
And be careful in using function call in your html as mentioned above. It preferred to use pipe instead of function call. Here is Stackblitz example. In first case function call will triggered on any change detection (example: clicking on buttons).
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