如何将正常的for循环复制到* ngFor [英] How to replicate normal for loop to *ngFor
本文介绍了如何将正常的for循环复制到* ngFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
rating = 4;
for(i=0; i < rating ; i++){
//print statement
}
如何使用* ngFor
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....
推荐答案
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屋!
查看全文