Подтвердить что ты не робот

Повторите элемент HTML несколько раз, используя ngFor на основе числа

Как использовать *ngFor для повторения элемента HTML несколько раз?

Например: Если у меня есть переменная-член, назначенная на 20. Как использовать директиву * ngFor, чтобы сделать повторение div 20 раз?

4b9b3361

Ответ 1

Вы можете использовать следующее:

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

Ответ 2

Есть две проблемы с рекомендуемыми решениями с использованием Arrays:

  1. Это расточительно. В частности для больших количеств.
  2. Вы должны определить их где-то, что приводит к большому беспорядку для такой простой и распространенной операции.

Кажется, более эффективно определить Pipe (один раз), возвращая Iterable:

import {PipeTransform, Pipe} from '@angular/core';

@Pipe({name: 'times'})
export class TimesPipe implements PipeTransform {
  transform(value: number): any {
    const iterable = <Iterable<any>> {};
    iterable[Symbol.iterator] = function* () {
      let n = 0;
      while (n < value) {
        yield ++n;
      }
    };
    return iterable;
  }
}

Пример использования (рендеринг сетки с динамической шириной/высотой):

<table>
    <thead>
      <tr>
        <th *ngFor="let x of colCount|times">{{ x }}</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let y of rowCount|times">
        <th scope="row">{{ y }}</th>
        <td *ngFor="let x of colCount|times">
            <input type="checkbox" checked>
        </td>
      </tr>
    </tbody>
</table>

Ответ 3

<div *ngFor="let dummy of ' '.repeat(20).split(''), let x = index">

Замените 20 вашей переменной

Ответ 4

Вы можете просто сделать это в своем HTML:

*ngFor="let number of [0,1,2,3,4,5...,18,19]"

И используйте переменную "число" для индексации.

Ответ 5

Более простое и многоразовое решение, возможно, для использования настраиваемой структурной директивы, подобной этой.

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appTimes]'
})
export class AppTimesDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }

  @Input() set appTimes(times: number) {
    for (let i = 0 ; i < times ; i++) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }

}

И используйте его следующим образом:

<span *appTimes="3" class="fa fa-star"></span>

Ответ 6

<ng-container *ngFor="let i of [].constructor(20)">🐱</ng-container>

генерирует 🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱

Ответ 7

Если вы используете Lodash, вы можете сделать следующее:

Импортируйте Lodash в ваш компонент.

import * as _ from "lodash";

Объявите переменную-член в компоненте для ссылки на Lodash.

lodash = _;

Тогда, по вашему мнению, вы можете использовать функцию диапазона. 20 можно заменить любой переменной в вашем компоненте.

*ngFor="let number of lodash.range(20)"

Нужно сказать, что привязка к функциям в представлении может быть дорогостоящей, в зависимости от сложности функции, которую вы вызываете, так как Обнаружение изменений будет вызывать функцию повторно.

Ответ 8

Упрощенный подход:

Определите helperArray и запрограммируйте его динамически (или статически, если хотите) с длиной подсчета, которую вы хотите создать ваши HTML-элементы. Например, я хочу получить некоторые данные с сервера и создать элементы с длиной возвращаемого массива.

export class AppComponent {
  helperArray: Array<any>;

  constructor(private ss: StatusService) {
  }

  ngOnInit(): void {
    this.ss.getStatusData().subscribe((status: Status[]) => {
      this.helperArray = new Array(status.length);
    });
  }
}

Затем используйте helperArray в моем HTML-шаблоне.

<div class="content-container" *ngFor="let i of helperArray">
  <general-information></general-information>
  <textfields></textfields>
</div>

Ответ 9

Вот немного улучшенная версия структурной директивы Ilyass Lamrani, которая позволяет использовать индекс в вашем шаблоне:

@Directive({
  selector: '[appRepeatOf]'
})
export class RepeatDirective {

  constructor(private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef) {
  }

  @Input()
  set appRepeatOf(times: number) {
    const initialLength = this.viewContainer.length;
    const diff = times - initialLength;

    if (diff > 0) {
      for (let i = initialLength; i < initialLength + diff; i++) {
        this.viewContainer.createEmbeddedView(this.templateRef, {
          $implicit: i
        });
      }
    } else {
      for (let i = initialLength - 1; i >= initialLength + diff ; i--) {
      this.viewContainer.remove(i);
    }
  }

}

Использование:

<li *appRepeat="let i of myNumberProperty">
    Index: {{i}}
</li>

Ответ 10

Самый эффективный и лаконичный способ добиться этого - добавить утилиту итератора. Не утруждайте себя ценностями. Не беспокойтесь об установке переменной в директиве ngFor:

function times(max: number) {
  return {
    [Symbol.iterator]: function* () {
      for (let i = 0; i < max; i++, yield) {
      }
    }
  };
}

@Component({
  template: '''
<ng-template ngFor [ngForOf]="times(6)">
  repeats 6 times!
</ng-template>

'''
})
export class MyComponent {
  times = times;
}