-2
rating = 4;
for(i=0; i < rating ; i++){ 
//print statement
}

how to replicate the same for loop with conditions in angular 6 using *ngFor

the loop should run based on the rating value.. if it is 2 it should run for 2 times....

Sravya
  • 65
  • 13
  • 1
    I would suggest you make the [tutorial](https://angular.io/tutorial) to learn the principles of angular. – Joniras Dec 19 '18 at 11:56
  • ngFor only works on lists etc it cant be used as for loop. https://stackoverflow.com/questions/36354325/angular-2-ngfor-using-numbers-instead-collections – Ans Bilal Dec 19 '18 at 11:57
  • 1
    Possible duplicate of [Angular 2 - NgFor using numbers instead collections](https://stackoverflow.com/questions/36354325/angular-2-ngfor-using-numbers-instead-collections) – Ans Bilal Dec 19 '18 at 11:57
  • i want to run the for loop based on the rating value.... – Sravya Dec 20 '18 at 05:45
  • @Sravya, just use < div *repeat="rating">< /div>. ("rating" is a variable in your .ts). If you need the "index", < div *repeat="ratting";let index>.. here you can use index.. div> – Eliseo Dec 20 '18 at 07:34

3 Answers3

1

I think you looking for this kind of solution, Just create one empty array with your rating length

component

let items = [];
for(i=0; i < rating ; i++){ 
 items.push(i);
}

Use in template like

<div *ngFor="let item of items">
</div>
yala ramesh
  • 3,362
  • 1
  • 22
  • 35
  • Hi @sravya above that code do the same thing right, if rating is '10' this loop will be run 10 times, what your use case? – yala ramesh Dec 20 '18 at 06:52
1

The best solution I think is using a directive like @pdudits say in the link. To improve the directive I propouse

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[repeat]'
})
export class RepeatDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }

  @Input() set repeat(times: number) {
    let count=this.viewContainer.length;
    for (let i=this.viewContainer.length;i>times;i--)
      this.viewContainer.remove(i-1);

    for (let i = count ; i < times ; i++) 
      this.viewContainer.createEmbeddedView(this.templateRef,
      {
        $implicit:i
      });

  }
}

You can use as

<div *repeat="40;let index">{{index}}</div>

See stackblitz

Eliseo
  • 50,109
  • 4
  • 29
  • 67
-1

You mean like <div *ngFor="let item of items; let i = index">{{ i }}</div>

  • as @ans-bilal already pointed out, this does the trick for an array (in this case items) but does not print 4 statements as questioned – Joniras Dec 19 '18 at 11:59