如何将正常的 for 循环复制到 *ngFor

编程入门 行业动态 更新时间:2024-10-22 08:31:38
本文介绍了如何将正常的 for 循环复制到 *ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 17:19:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1027013.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   ngFor

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!