Angular Structural Directives are used to add and remove items to the DOM. The three Angular directives we will talk about in this video is the ngIf, the ngSwitch, and the ngFor directives.

The ngIf directives allows you to add and remove items to the DOM by using an expression that results in a Boolean result. The syntax for the ngIf directive is as follows:

*ngIf=”expession”

If the expression is false, then the element the directive is defined on will be removed from the DOM. If the expression result is true, the element will be added to the DOM.

You can also provide templates to use as an else clause:

*ngIf=”expression; then thenBlockTemplate; else elseBlockTemplate”

The ngSwitch directive allows you to compare a single expression against many expressions. This is similar to a Switch/Case statement in C#. Start by defining a top level DIV and use the ngSwitch directive

[ngSwitch]=”expression”

Then for each element in the statement use the ngSwitchCase

*ngSwitchCase=”expression”

Lastly, you can provide a default element by using the ngSwitchDefault

*ngSwitchDefault

Lastly, you can use the ngFor directive to loop through a collection of object and add an element to the DOM for each item in the collection.

Start with a collection of objects:

makes = [“Chevy”, “Ford”, “GMC”, “Dogdge”]

Then loop trhough the collection using the ngFor

*ngFor=”let make of makes”

Finally, use interpolation to bind to the item in the for loop

{{ make }}

That’s all there is to it!

Brian Lagunas

View all posts

Add comment

Your email address will not be published. Required fields are marked *

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.