Skip to content

Instantly share code, notes, and snippets.

@nivrith
Last active June 18, 2022 11:17
Show Gist options
  • Save nivrith/75b7580bbd592cdfbde72a242aa07bb4 to your computer and use it in GitHub Desktop.
Save nivrith/75b7580bbd592cdfbde72a242aa07bb4 to your computer and use it in GitHub Desktop.
Repeat angular template based on a number rather than an iterable
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
export type RepeatTimesContext = {
$implicit: number;
index: number;
}
@Directive({
selector: '[repeatTimes]'
})
export class RepeatTimesDirective {
static ngTemplateContextGuard(
dir: RepeatTimesDirective, ctx: unknown
): ctx is RepeatTimesContext { return true; };
constructor (
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) { }
@Input('repeatTimes') set count(count: number) {
this.viewContainer.clear();
for (let i = 0; i < count; i++) {
this.viewContainer.createEmbeddedView<RepeatTimesContext>(this.templateRef, { $implicit: i, index: i });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment