Controlling the DOM: The Power of Structural Directives
Angular applications are dynamic. Elements appear, disappear, and duplicate based on user interaction and data. The tools that allow you to manipulate the DOM layout by adding, removing, and manipulating elements are called **Structural Directives**.
The Asterisk (*): Syntactic Sugar
You've likely noticed that directives like `*ngIf` and `*ngFor` are prefixed with an asterisk. This isn't just decoration. It's shorthand that tells Angular to wrap the host element in an <ng-template> .
What You Write
<div *ngIf="hero" class="name">
{{hero.name}}
</div>What Angular Compiles
<ng-template [ngIf]="hero">
<div class="name">
{{hero.name}}
</div>
</ng-template>Performance: `*ngIf` vs `[hidden]`
New developers often confuse `*ngIf` with the `[hidden]` attribute. While they appear visually similar, they function very differently:
- *ngIf: Physically removes the element from the DOM. If the condition is false, the component is destroyed, freeing up memory and resources.
- [hidden]: Merely sets `display: none` via CSS. The element remains in the DOM and the component stays alive.
Best Practice: Use `*ngIf` by default, especially for large trees of components. Use `[hidden]` only if the toggle cost is high and you need to keep the state of the component alive while it is invisible.
Optimizing Lists with `trackBy`
When using `*ngFor` to iterate over large lists fetched from an API, Angular has to re-render the DOM whenever the list reference changes. This can be expensive.
By using a `trackBy` function, you tell Angular how to identify unique items (usually by ID). This allows Angular to only update the DOM elements that have actually changed, rather than destroying and recreating the entire list.
Key Takeaway: Structural directives are powerful tools for managing your view. Understand the cost of DOM manipulation and use tools like `trackBy` and `ngSwitch` to keep your application performant.