如何将正常的 for 循环复制到 *ngFor [英] How to replicate normal for loop to *ngFor

查看:20
本文介绍了如何将正常的 for 循环复制到 *ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何使用 *ngFor 以 6 角的条件复制相同的 for 循环

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

循环应该根据评级值运行..如果它是 2,它应该运行 2 次..

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

推荐答案

我认为最好的解决方案是使用像@pdudits 这样的指令 say 在链接中.为了改进我提出的指令

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
      });

  }
}

你可以用作

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

参见 stackblitz

这篇关于如何将正常的 for 循环复制到 *ngFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆