Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check in template if variable is an array, string, number

I have a items array as shown below inside parent component.ts file

items = [
    {text: 'Length' , value: 10 },
    {text : 'Degree' , value : "108"},
    {text : 'Edges' , value : [10,20,30]}
]

Then I have a component named app-label-values placed inside a *ngFor Loop in parent component like show below

<div *ngFor ="let item of items">
  <app-label-values
   label="item.text"
   value = "item.value">
  </app-label-values>
</div>

app-label-values component purpose is to display label and value corresponding to the label.

For eg. Age : 10

The label here will always be a text while the type of value can be dynamic ( number, strings, arrays)

So when the value is of type array I need to show only the length of the array ,like in our case the component should display 'Edges : 3' since [10,20,30].length is 3.

My aim is not to have this logic of type checking in the app-label-values component as I need it to be dumb and display only what is passed to it.

How can I solve this from parent component itself while rendering.

Kindly help.Thanks in advance.

like image 960
Shijil Narayanan Avatar asked Sep 17 '25 16:09

Shijil Narayanan


1 Answers

You can use an ngIf to check if the item.value has a length property. In the parent component,you can still pass to the child item.value and in the child component you display the value depending on the fact that it is an array or a number

  1. check length property
   <div *ngIf="item.value?.length > {{item.value.length}} </div>

If you want to pass directly the length of array to your child component, you can consider using a ternary operator

value="item.value?.length ? item.value.length : item.value"

If you want to check for string value, you first check if there is a length property. Then one can use the + operator to parse the string. And with a second ternary operator, you can check if that is a number or an array

value="item.value?.length ? +item.value ? item.value : item.value.length : item.value" 
  1. check constructor name
value="item.value.constructor.name === "Array" ? item.value.length : item.value"

Using the constructor, one can check also if the value is a string, number, etc.. live code

like image 93
edkeveked Avatar answered Sep 20 '25 05:09

edkeveked