Angular FAQ: Top Questions
16. What is a Structural Directive in Angular?
In Angular, structural directives are special directives that alter the structure of the DOM by adding, removing, or manipulating elements. These directives are typically prefixed with an asterisk *
and are responsible for shaping how Angular renders content conditionally or repetitively in the template.
Unlike attribute directives (which change the appearance or behavior of existing elements), structural directives modify the DOM layout. They dynamically control which HTML elements appear based on logic in the component.
-
Syntax and Convention:
-
Structural directives use shorthand syntax like
*ngIf
and*ngFor
, which Angular desugars into an extended<ng-template>
representation under the hood. -
Example:
<div *ngIf="condition">
is equivalent to placing a directive on an<ng-template>
element.
-
Structural directives use shorthand syntax like
-
Common Structural Directives:
*ngIf
– Conditionally includes a template block when the expression evaluates to true.*ngFor
– Iterates over a collection and renders a template for each item.*ngSwitch
– Conditionally switches among multiple templates usingngSwitchCase
andngSwitchDefault
.
-
Custom Structural Directives:
-
Developers can create their own structural directives by manipulating the view using
ViewContainerRef
andTemplateRef
. - These custom directives follow the same Angular lifecycle and can enable advanced layout control.
-
Developers can create their own structural directives by manipulating the view using
// app.component.ts
export class AppComponent {
isLoggedIn = true;
items = ['Angular', 'React', 'Vue'];
}
// app.component.html
<div *ngIf="isLoggedIn">Welcome, User!</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
Explanation of the Example Code:
-
The
*ngIf="isLoggedIn"
directive conditionally includes the welcome message only whenisLoggedIn
istrue
. -
The
*ngFor
directive iterates over theitems
array and creates a list item<li>
for each value. - Both directives modify the DOM structure at runtime depending on data or logic defined in the component class.
Structural directives are powerful tools for building dynamic UIs in Angular, allowing developers to declaratively control what gets rendered based on component state or data collections.