有角度 – 使用ngFor多次重复HTML元素

前端之家收集整理的这篇文章主要介绍了有角度 – 使用ngFor多次重复HTML元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用* ngFor多次重复HTML元素?

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

解决方法

您可以使用以下内容
  1. @Component({
  2. (...)
  3. template: `
  4. <div *ngFor="let i of arr(num).fill(1)"></div>
  5. `
  6. })
  7. export class SomeComponent {
  8. arr = Array; //Array type captured in a variable
  9. num:number = 20;
  10. }

或实现自定义管道:

  1. @Pipe({
  2. name: 'fill'
  3. })
  4. export class FillPipe implements PipeTransform {
  5. transform(value) {
  6. return (new Array(value)).fill(1);
  7. }
  8. }
  9.  
  10. @Component({
  11. (...)
  12. template: `
  13. <div *ngFor="let i of num | fill"></div>
  14. `,pipes: [ FillPipe ]
  15. })
  16. export class SomeComponent {
  17. arr:Array;
  18. num:number = 20;
  19. }

猜你在找的HTML相关文章