How to replicate normal for loop to *ngFor

爱⌒轻易说出口 提交于 2020-01-07 09:31:14

问题


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


回答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>



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/53850607/how-to-replicate-normal-for-loop-to-ngfor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!