somebody maybe encounter some situation when use the ngFor
without collections.But seems looks like every one like to set the variable of array
and let *ngFor
binding like following code:
array
// typescript
public bignumber:number[]=[1,2,3,4,5,6,7,8,9,10]
//html
<ng-template *ngFor="let item of bignumber | index as i">
p {{i}}
<!-- would show ten times -->
</ng-template>
It's not friendly for template when you want to run 5 times or 10 times and you need to set the new varible then you can iterator.So I want to use Array
new Array
in template but it didn't work.No matter new Array()
or any you would use the keyword Array
, it would parse the our variable but not the specify keyword.
error log
ERROR TypeError: _co.Array is not a function
Now I use the complex way to solve this situation:
template
<ng-template [ngForOf]="[].map.call({length:10},[].map).fill('')" let-i="index">
p {{i}}
<!-- show 10 times -->
</ng-template>
Is any possible use the cleary code like:
[ngForOf]="Array(10).fill()"
AFAIK Angular doesn't support
Array
constructor in template.To work around it you could try the following:
Template only solutions
1)
String.prototype.repeat()
2) Using
ngTemplateOutlet
3) Using
NgIf
Declaring Array property on component
You can also create
Array
property on your component:and then
Stackblitz Example
And you can always create your own pipe:
See also