Structural Directives
Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.
As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.
Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.
What are structural directives?
Manipulate a components template
Can hide or remove components and elements
Iterate over arrays and execute a portion of the template for each instance
Examples
ngFor
ngIf
ngSwitch
Structural Directive Examples
The asterisk (*) notation is a convenience notation and the string part is a micro-syntax.
*ngIf Directive
Remove vs Hide
Component behavior continues even when hidden
Showing a hidden element is very fast
Prefer removal over hiding components
Asterisks Prefix
Angular translates the *ngIf directive into a <ng-template> element
*ngFor Directive
*ngFor enumerates over an array and returns each individual item. The outer element is repeated for each item returned.
Acccess variables like index and odd for special formatting
trackBy
function can improve performance for insertion and deletiontrackById(index, item) { return item.id }
Helps Angular find items faster by using the unique id
ngSwitch Directive
Is a set of co-operative directives: `ngSwitch, ngSwitchCase, ngSwitchDefault`. The value assigned to ngSwitch determines which switch cases are displayed. ngSwitch is actually an attribute directive and controls the behavior of the other two structural directives.
Create Custom Structural Directive
We will create a custom structural directive UnlessDirective
that is opposite of the ngIf
directive. It will show it's content if it's condition is false.
Let's create a new directive using ng g d unless
to generate the directive.
Summary
Structural directives including *ngIf, *ngFor, and ngSwitch
The asterisk prefix
How ng-template is used
How to create a custom strucural directive
Last updated