Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get length of array in template syntax

Tags:

I am trying to evaluate the below in template syntax which is an array:

FAIL  {{ cols.length }} 

I get the below error.

platform-browser.umd.js:1900 ORIGINAL EXCEPTION: TypeError: Cannot read property 'length' of undefined 

But I do iterate so I know that portion works:

      SUCCESS      <th *ngFor="let h of cols">          {{h}}       </th> 
like image 621
Tampa Avatar asked Aug 19 '16 22:08

Tampa


People also ask

How do you find the length of an array?

Using sizeof() function to Find Array Length in C++ Hence, if we simply divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.

What is the length of the array?

Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array. Property Value: This property returns the total number of elements in all the dimensions of the Array. It can also return zero if there are no elements in the array.

How do you find the length of an array in HTML?

To find the length of an array, reference the object array_name. length. The length property returns an integer.

How to see length of array in Python?

To find the length of an array in Python, we can use the len() function. It is a built-in Python method that takes an array as an argument and returns the number of elements in the array. The len() function returns the size of an array.


2 Answers

Use

{{ cols?.length }} 

Or

<div *ngIf="cols">{{ cols.length }}</div> 

If you want to print 0 for empty array, use

{{ cols?.length || '0' }} 

Reason: cols is not initiated when Angular2 load the template. And we want to wait until it's ready to access its members.

like image 151
Harry Ninh Avatar answered Sep 23 '22 07:09

Harry Ninh


Try defining the cols variable as an object list on .ts archive cols: object[];

If you want to print 0 for an empty array use the ternary operator:

{{ cols ? cols.length : '0' }} 
like image 34
Ignacio Perez Roca Avatar answered Sep 26 '22 07:09

Ignacio Perez Roca