Types of Directives
Components
Directives with templates
Structural
Change DOM layout (add/remove elements)
Attribute
Change appearance or behavior of elements
Built-in Structural Directives
Modern Angular uses built-in control flow (
@if, @for, @switch) instead of structural directives. These are still available for compatibility.*ngIf (Legacy)
*ngFor (Legacy)
*ngSwitch (Legacy)
Built-in Attribute Directives
ngClass
Dynamically add/remove CSS classes:ngStyle
Dynamically set inline styles:ngModel
Two-way data binding for form inputs:Custom Attribute Directive
Create your own attribute directive:Custom Structural Directive
Create a custom structural directive:Directive with Multiple Inputs
Host Bindings and Listeners
Usehost metadata for cleaner directives:
Directive Composition
Apply multiple directives to a single host:Best Practices
- Use modern control flow - Prefer
@if,@for,@switchover*ngIf,*ngFor,*ngSwitch - Keep directives focused - Single responsibility
- Use host metadata - Instead of
@HostBindingand@HostListener - Make directives standalone - Better tree-shaking
- Provide meaningful selectors - Use attribute selectors with a prefix
- Document behavior - Clear documentation for custom directives
Next Steps
Templates
Learn template syntax and bindings
Components
Understand component architecture
