0 day streak
javascript / expert
Snippet

Advanced DOM Orchestration with Structural Directives

Structural directives allow for direct manipulation of the DOM by using `ViewContainerRef` (the container where the view is hosted) and `TemplateRef` (the HTML content of the directive). By manually clearing and creating embedded views, you can implement custom control flow logic that behaves exactly like `*ngIf` or `*ngFor`.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
@Directive({ selector: '[appExpertRepeat]', standalone: true })
export class ExpertRepeatDirective {
private vcr = inject(ViewContainerRef);
private template = inject(TemplateRef);
@Input() set appExpertRepeat(count: number) {
this.vcr.clear();
for (let i = 0; i < count; i++) {
this.vcr.createEmbeddedView(this.template, { $implicit: i });
}
}
}
angular
Breakdown
1
this.vcr.createEmbeddedView(this.template, { $implicit: i });
Instantiates the template inside the container and passes a context object for the 'let-i="index"' syntax.
2
this.vcr.clear();
Removes all existing views from the container to prevent duplication during input changes.