如何使用*ngFor多次重复HTML元素?

例如:
如果我有一个分配给20的成员变量,如何使用* ngFor指令使div重复20次?

最佳答案

您可以使用以下内容:

@Component({
  (...)
  template: `
    <div *ngFor="let i of Arr(num).fill(1)"></div>
  `
})
export class SomeComponent {
  Arr = Array; //Array type captured in a variable
  num:number = 20;
}

或实现自定义管道:
import {PipeTransform, Pipe} from '@angular/core';

@Pipe({
  name: 'fill'
})
export class FillPipe implements PipeTransform {
  transform(value) {
    return (new Array(value)).fill(1);
  }
}

@Component({
  (...)
  template: `
    <div *ngFor="let i of num | fill"></div>
  `,
  pipes: [ FillPipe ]
})
export class SomeComponent {
  arr:Array;
  num:number = 20;
}

关于angular - 根据数字使用ngFor多次重复HTML元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36535629/

10-09 06:52
查看更多