Как использовать *ngFor
для повторения элемента HTML несколько раз?
Например: Если у меня есть переменная-член, назначенная на 20. Как использовать директиву * ngFor, чтобы сделать повторение div 20 раз?
Как использовать *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;
}
Есть две проблемы с рекомендуемыми решениями с использованием Arrays
:
Кажется, более эффективно определить 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>
<div *ngFor="let dummy of ' '.repeat(20).split(''), let x = index">
Замените 20
вашей переменной
Вы можете просто сделать это в своем HTML:
*ngFor="let number of [0,1,2,3,4,5...,18,19]"
И используйте переменную "число" для индексации.
Более простое и многоразовое решение, возможно, для использования настраиваемой структурной директивы, подобной этой.
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>
<ng-container *ngFor="let i of [].constructor(20)">🐱</ng-container>
генерирует 🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱
Если вы используете Lodash, вы можете сделать следующее:
Импортируйте Lodash в ваш компонент.
import * as _ from "lodash";
Объявите переменную-член в компоненте для ссылки на Lodash.
lodash = _;
Тогда, по вашему мнению, вы можете использовать функцию диапазона. 20 можно заменить любой переменной в вашем компоненте.
*ngFor="let number of lodash.range(20)"
Нужно сказать, что привязка к функциям в представлении может быть дорогостоящей, в зависимости от сложности функции, которую вы вызываете, так как Обнаружение изменений будет вызывать функцию повторно.
Упрощенный подход:
Определите 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>
Вот немного улучшенная версия структурной директивы 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>
Самый эффективный и лаконичный способ добиться этого - добавить утилиту итератора. Не утруждайте себя ценностями. Не беспокойтесь об установке переменной в директиве 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;
}