Angular Directives

Structural Directives


Structural Directives

Structural directives are prefixed with an asterisk when being used which signals to Angular that the structure of the DOM elements within the directive may change depending on certain conditions. The two most common structural directives you'll come across are ngIf and ngFor. ngIf will remove the element if the expression assigned to it is falsy. ngFor will add or remove elements to the DOM depending on how many elements are in the iterable it's given.

In AngularJS there was the ng-show and ng-hide directives, which would show or hide elements depending on what the given expression evaluates to by setting the display CSS property. The difference between this behavior and ngIf is that ngIf will actually remove the elements/components entirely from the DOM, whereas ng-show and ng-hide will keep the elements/components there, so any component behaviors may keep running (e.g. listeners) even though the component isn't visible. While there aren't built-in directives for ng-show and ng-hide, you can get the same functionality by simply binding to the style.display property on the element.

For example:

<div *ngFor="let char of name.split(''), let i = index">
  {{ i }} - {{ char }}

This ngFor directive will loop through all of the characters in the name variable and output them along with the current index — thus creating (and if the name variable changes at all) removing elements from the DOM!

Additional Reading

Structural Directive Guide


I finished! On to the next chapter