Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4: How do I *ngFor, for every number in an int?

I have an int property named "count" in my component.

I would like to display a p tag X amount of times, where X is the int my count property equals. Is there really no simple way to do this, besides messing with fake arrays?

like image 855
Amivit Avatar asked Jun 13 '17 09:06

Amivit


People also ask

Which is the correct statement to fetch the index value in * ngFor?

Declare a variable inside *ngFor directive using let or as keyword. for instance say indexofelement or simply i . Assign the variable value to index .

How do you write ngFor?

The syntax is *ngFor="let <value> of <collection>" . <value> is a variable name of your choosing, <collection> is a property on your component which holds a collection, usually an array but anything that can be iterated over in a for-of loop.

Which directive can you use to loop through elements?

The built-in v-for directive allows us to loop through items. We can use a range in the v-for directive to iterate a specified number of times.

How do you use ngFor?

To Use ngFor directive, you have to create a block of HTML elements, which can display a single item of the items collection. After that you can use the ngFor directive to tell angular to repeat that block of HTML elements for each item in the list.


1 Answers

You could easily do it with an pipe filter which transforms an empty array to an number of childs depending on a filter param = number.

Pipe filter

import { Pipe, PipeTransform } from '@angular/core';  

@Pipe({  
    name: 'range',  
    pure: false  
})  

export class RangePipe implements PipeTransform {  
    transform(items: any[], quantity: number): any {  
      items.length = 0;
      for (let i = 0; i < quantity; i++) {
        items.push(i);
      }
      return items;
    }  
}  

View

<div *ngFor="let n of [] | range:100"></div>
like image 165
lin Avatar answered Sep 30 '22 21:09

lin