Structural Directives

In this lesson, we'll learn about how to use directives to conditionally render elements.

There’s one final touch we’ll add to the application. Below the button, the text Reversed Text appears regardless if there’s text to reverse or not. It would be ideal if we could hide the element until there’s something to reverse. We can do just that using directives.

Directives

A directive is a special attribute used to change the appearance or behavior of an element. There are two types of directives you’ll commonly use in your template.

Structural directives

The first type is structural directives. These directives have the power to change the layout of the DOM by adding/removing elements. They can be identified by the * character before the name of the attribute.

Attribute directives

The second type is attribute directives. They can change the appearance or behavior of a DOM element.

ngIf

Let’s use a directive in action. We can hide an element with the ngIf directive, which is a structural directive. We’ll apply it to the <div> element wrapped around the reversedText expression in the app.component.html file.

<div *ngIf="reversedText.length">
  Reversed Text: {{ reversedText }}
</div>

The format for using structural directives is an asterisk (*), followed by the name of the directive. The value for the directive will be an expression that can evaluate to either true or false. The ngIf directive will add an element to the document if the expression evaluates to true. Otherwise, it will hide the element. It’s similar to how conditional statements work in JavaScript. The main difference is that we can apply this logic directly on an element.

In this example, we’re checking the length property on the reversedText property. The length property of strings will return 0 if there are no characters in the string. This is the same as false. A a result, the element is removed from the document.

Directives are a great way to make a document interactive. Let’s see them in action. In the widget below, the <div> element is hidden. We won’t be able to see it until we type in the input and click the button.

Get hands-on with 1200+ tech skills courses.