Last active
June 18, 2022 11:17
-
-
Save nivrith/75b7580bbd592cdfbde72a242aa07bb4 to your computer and use it in GitHub Desktop.
Repeat angular template based on a number rather than an iterable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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