...for example...
<div class="month" *ngFor="#item of myCollection; #i = index"> ... </div>
Is possible to do something like...
<div class="month" *ngFor="#item of 10; #i = index"> ... </div>
...without appeal to a non elegant solution like:
<div class="month" *ngFor="#item of ['dummy','dummy','dummy','dummy','dummy', 'dummy','dummy','dummy']; #i = index"> ... </div>
?
You can't use multiple *ngFor s in the same element as those are structural directives and angular handles them in a specific way (basically for each structural directive it creates an ng-template element which then holds the directive itself, you can read more about it here: https://angular.io/guide/structural- ...
*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.
ngForOf: NgIterable<T> : The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe ( userStreams | async ). index: number : The index of the current item in the iterable.
The *ngFor directive is used to repeat a portion of HTML template once per each item from an iterable list (Collection). The ngFor is an Angular structural directive and is similar to ngRepeat in AngularJS. Some local variables like Index, First, Last, odd and even are exported by *ngFor directive.
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent { constructor() { this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4] this.numbers = Array(5).fill(4); // [4,4,4,4,4] } }
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@Component({ template: ` <ul> <li *ngFor="let number of numbers">{{number}}</li> </ul> ` }) export class SampleComponent { (...) }
Or shortly:
@Component({ template: ` <ul> <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li> </ul> ` }) export class SampleComponent { (...) }
@OP, you were awfully close with your "non-elegant" solution.
How about:
<div class="month" *ngFor="let item of [].constructor(10); let i = index"> ... </div>
Here I'm getting the Array
constructor from an empty array: [].constructor
, because Array
isn't a recognized symbol in the template syntax, and I'm too lazy to do Array=Array
or counter = Array
in the component typescript like @pardeep-jain did in his 4th example. And I'm calling it without new
because new
isn't necessary for getting an array out the Array
constructor.
Array(30)
and new Array(30)
are equivalent.
The array will be empty, but that doesn't matter because you really just want to use i
from ;let i = index
in your loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With