๐งฑ What Are Structural Directives?
Structural directives are used to change the structure of the DOM — by adding, removing, or manipulating elements in the template.
Examples of built-in structural directives:
-
*ngIf
-
*ngFor
-
*ngSwitch
They use the *
prefix and typically manipulate the host element and its view in the DOM.
๐งฐ What Are Custom Structural Directives?
A custom structural directive lets you create your own logic to control how and when certain parts of the DOM appear.
For example, a custom directive called *appUnless
could behave as the opposite of *ngIf
.
✅ How to Implement One — Step-by-Step
๐งช Example: *appUnless
Directive
1. Create the Directive
2. Code Implementation
๐ก How It Works:
-
TemplateRef
: Represents the element the directive is applied to. -
ViewContainerRef
: Container that holds views — allows us to insert or remove them. -
@Input()
: Binds the directive’s value (like*appUnless="isLoggedIn"
).
๐งช Usage in Template
If isLoggedIn
is false, the content appears — the reverse of *ngIf
.
๐ง Summary
Aspect | Structural Directive |
---|---|
Modifies DOM? | ✅ Yes — adds/removes elements dynamically |
Prefix | Typically used with * |
Uses | TemplateRef , ViewContainerRef , @Input |
Example | *ngIf , *ngFor , *appUnless |