How to replicate normal for loop to *ngFor

前端 未结 3 1074
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 13:34
rating = 4;
for(i=0; i < rating ; i++){ 
//print statement
}

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

th

相关标签:
3条回答
  • 2021-01-29 14:12

    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

    0 讨论(0)
  • 2021-01-29 14:15

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

    0 讨论(0)
  • 2021-01-29 14:22

    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>
    
    0 讨论(0)
提交回复
热议问题