javascript / intermediate
Snippet
Custom Structural Directives
Structural directives manipulate the DOM layout by adding, removing, or manipulating elements. Unlike attribute directives, they use a TemplateRef to capture the element's content and a ViewContainerRef to manage where it is rendered. This example creates a delay before rendering the content.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Directive({selector: '[appDelay]',standalone: true})export class DelayDirective implements OnInit {@Input() appDelay!: number;constructor(private templateRef: TemplateRef<any>,private viewContainer: ViewContainerRef) {}ngOnInit() {setTimeout(() => {this.viewContainer.createEmbeddedView(this.templateRef);}, this.appDelay);}}
angular
Breakdown
1
private templateRef: TemplateRef<any>
References the HTML content inside the element where the directive is applied.
2
this.viewContainer.createEmbeddedView(...)
Programmatically renders the captured template into the DOM.