Structural directives in Angular (*ngIf, *ngFor, *ngSwitch) modify the DOM structure by controlling the presence of elements.
How They Work:
They use ViewContainerRef and TemplateRef to add or remove elements dynamically.
Example: Custom Directive (appExample)
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
@Directive({
selector: '[appExample]'
})
export class ExampleDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
@Input() set appExample(condition: boolean) {
condition ? this.viewContainer.createEmbeddedView(this.templateRef) : this.viewContainer.clear();
}
}