Parse an array in an angular pattern

someone might run into some kind of situation when using ngFor without collections. But it seems that everyone likes to set the array variable and bind *ngFor as the following code:

an 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> 

This is not suitable for a template, if you want to run 5 or 10 times, and you need to set a new variable, then you can iterate. So I want to use array new array in the template, but this is not work. No matter new Array() or any that you would use with the array keyword, it will parse our variable, but not the define keyword.

error log

ERROR TypeError: _co.Array is not a function

Now I am using a complicated 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 it possible to use clean code, for example:

 [ngForOf]="Array(10).fill()" 
0
angular angular2-template
Dec 01 '17 at 4:10
source share
1 answer

AFAIK Angular does not support the Array constructor in the template.

To get around this, you can try the following:

Template 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 an Array Property for a Component

You can also create an Array property for 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> 

Stackblitz example

And you can always create your own channel:

see also

  • Repeat the HTML element several times using ngFor based on the number
+1
Dec 01 '17 at 4:35 on
source share



All Articles