Directives are special markers in your HTML templates that tell Angular to attach specific behaviors to DOM elements.
In fact, Angular Components are actually just directives with an attached template view!
Angular provides numerous built-in directives, categorized into two main types: Structural and Attribute directives.
Structural directives fundamentally alter the layout of the DOM by adding, removing, or replacing HTML elements.
You can easily identify structural directives because they are always prefixed with an asterisk (*).
The two most important structural directives are *ngIf and *ngFor.
<!-- Conditionally renders the div based on a boolean --> <div *ngIf="isLoggedIn">Welcome back to your dashboard!</div><!-- Loops through an array and renders a list item for each --> <ul> <li *ngFor="let item of shoppingList">{{ item }}</li> </ul>
We will cover both of these powerful directives in depth in upcoming chapters.
Attribute directives alter the appearance or behavior of an existing DOM element, without removing it from the document.
They are applied like normal HTML attributes and usually rely on property binding [ ].
The most common built-in attribute directives are ngClass and ngStyle.
<!-- Dynamically adds the 'highlight' class if isImportant is true -->
<p [ngClass]="{ 'highlight': isImportant }">
This paragraph's class changes dynamically!
</p>
<!-- Dynamically applies inline CSS styles -->
<div [ngStyle]="{ 'background-color': statusColor, 'font-size': '20px' }">
This box's background color depends on a variable.
</div>
While the built-in directives are extremely powerful, you are not limited to them.
Angular allows you to create your own Custom Directives to execute complex logic when elements are rendered.
For instance, you could create a custom appHighlight directive that changes the background color of any element when hovered over!
You can generate a custom directive quickly using the CLI command: ng generate directive my-directive.
Which symbol must always prefix an Angular Structural Directive like ngIf or ngFor?
What is the primary difference between a Structural and an Attribute directive?