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) [].constructor(10)
2) String.prototype.repeat()
<ng-container *ngFor="let item of ' '.repeat(2).split(''), let i = index ">
p {{i}}
</ng-container>
3) Using ngTemplateOutlet
<ng-container *ngTemplateOutlet="tmpl; context: { $implicit: 0 }"></ng-container>
<ng-template #tmpl let-i>
<div>
Your template here {{ i }}
</div>
<ng-container *ngIf="i < 10">
<ng-container *ngTemplateOutlet="tmpl; context { $implicit: i + 1 }"></ng-container>
</ng-container>
</ng-template>
3) Using NgIf
<ng-container *ngIf="1; then tmpl"></ng-container>
<ng-template #tmpl let-i>
<div>
Your template here {{ i }}
</div>
<ng-container *ngIf="i < 10">
<ng-container *ngIf="i + 1, then tmpl"></ng-container>
</ng-container>
</ng-template>
Declaring Array property on component
You can also create Array
property on your component:
export class AppComponent {
Array = Array;
}
and then
<ng-container *ngFor="let item of Array.apply(null, Array(2)), let i = index ">
p {{i}}
</ng-container>
<br>
<ng-container *ngFor="let item of Array(2).fill(), let i = index ">
p {{i}}
</ng-container>
And you can always create your own pipe:
See also
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.