Angular helps build views that are declarative and use HTML markup. Angular helps reuse most HTML elements and features. It helps extend functionality, making it a powerful framework.
This chapter describes various types of directives. It lists some of Angular’s most popular built-in directives. The directives help code conditional logic in the HTML template, iterate through the collections, and apply the styles dynamically.
Directives
Angular provides the ability to augment the HTML template and provide additional features and functionalities. Directives play an important role. There are three categories of directives in Angular.
Components : This type of directive allows you to create custom elements. It is a powerful feature that provides maximum reusability of the Angular application. It is arguably the most widely used feature in Angular. There is an entire chapter dedicated to components in this book.
Structural directives: This type of directive allows you to customize and modify the structure of a view. For example, a list of the superheroes is a view. You may use a directive to iterate through an available list of superheroes and show them in an ordered list. As another example, imagine that the contact information about a superhero is hidden by default. You can show it conditionally when the user requests it.
Conditionally showing or hiding contact information is a structural change to the superhero view. Iterating through the superhero list and showing the available superheroes in a list is structural.
Attribute directives: Attribute directives augment an element’s behavior and view. It may add additional functionalities to the element. ngStyle is an example of an attribute directive. A section in this chapter describes this directive.
This chapter discusses the built-in directives in Angular. They are powerful and used often in building web applications.
Using the ng-template Directive in the HTML Template
ng-template is an Angular element. You may use it to refer to a block in an HTML template. It is useful for showing or hiding a section of the component or for using a block of HTML in one or more places in the template.
You may use a template reference variable to provide a name for a block of HTML. In Listing 6-1, a component that shows superhero information, a section of contact information is wrapped in ng-template (see lines 8 to 13). A template reference variable is provided to refer to the contents (see #heroContactDetails in line 8).
Note
Refer to the @ViewChild() implementation in Chapter 4 to learn about using a template reference variable in a TypeScript file component.
The block of HTML in lines 8 to 13 do not show when the page loads. It is a block of HTML waiting to be used. Refer to line 5, which has the ngTemplateOutlet structural directive. It refers to heroContactDetails, the template reference variable defined in line 8. Hence, the block of HTML for the superhero contact information is rendered in line 5.
Usage on ng-template in the Superhero Component
Using if…else Conditions in the HTML Template
To incorporate conditional logic in the HTML template, we can use the ∗ngIf directive. It is a structural directive. Imagine that we want to show or hide part of a component conditionally. Let’s enhance Listing 6-2. Consider showing the superhero contact information when the user explicitly selects a check box. By default (or when the user unselects the check box), contact information is hidden.
Show Elements When Conditional
Note
Structural directives are prefixed with an asterisk (*).
Check Box to Switch the True/False Condition
Let’s improve this sample code by adding an else condition. Show a message that the contact information is hidden when the check box is unselected. Listing 6-4 adds an else condition to the directive. Note the else condition that uses the hiddenText template. The HTML code between lines 8 and 11 is for the message text.
Else Condition for Superhero Contact Details
Note
Listing 6-4 uses a Boolean variable, showContacts, which can be true/false. Any conditional statement that returns true/false can be used with *ngIf.
Using the ng-container Directive in the HTML Template
ng-container wraps HTML elements. Typically, HTML elements are wrapped in elements like <div>, <span>, <p>, and so forth; however, applications might use specific styles that are predefined when these elements are used. For example, there could be a global style on a web application that applies certain margins and padding to a div element. This style might interfere when attempting to wrap a set of elements in your component. To address this scenario, you could use ng-container. It does not show as an element in HTML when rendered in a browser; hence, there is no style applied that interferes with the set of elements it encapsulates.
Refer to the first lines of Listing 6-3 and Listing 6-4. A div is used as a placeholder for the conditional logic; either #contactDetails template or #hiddenText template is shown in its place. If the div uses a global style, it is applied here as well. You may use ng-container instead of a div here.
Simplified Conditional Logic
Note that ∗ngIf="showContacts; then contactDetails else hiddenText" is simplified to ∗ngIf="showContacts else hiddenText".
Using a Switch Case in the HTML Template
ngSwitch: The variable to be compared with values.
ngSwitchCase: One of the many values to be compared. Typically, a series of ngSwitchCase directives are used.
ngSwitchDefault: The default value when none of the values matches.
Switch/Case to Conditionally Verify Multiple Values
Refer to line 2 in Listing 6-7. The ngSwitch directive checks the equality condition in the birthplace variable. If the value provided in the text field (line 1) matches any value provided between lines 3 and 8, the respective value is shown. The ngSwitch variable is compared to the ngSwitchCase value. In the sample, we are using string values. The values Dholakpur, Kryptonopolis, and so forth, are not data bound with a variable.
Iterate Through an Array in the HTML Template
List of Superheroes in the TypeScript File Component
A shorthand form of ∗ngForOf directive is often used. Listing 6-8 iterates through the superheroes and shows the values in a list. We create a hero variable that represents each hero string with let hero of superheroes. Considering that a hero is a simple string, we show the value with interpolation data binding ({{hero}}).
Note
If superheroes is an array of objects, the hero local variable would be an individual object in the array. You may use the hero.fieldName syntax to show a field.
Iterate Through Superheroes in HTML Template
ngForOf with Superheroes Array
Local Variables with ngFor
index: Stores a zero-based index number for each iteration
first: Sets to true if it is the first iteration.
last: Sets to true if it is the last iteration.
even: Sets to true if it is an even iteration.
odd: Sets to true if it is an odd iteration.
Listing 6-10 makes use of these variables. In the first line, each local variable is aliased to be used; for example, index is i. Line 2 shows item numbers. We increment by one because it is a zero-based index.
Show Local Variables
Note
Note [ngIf]="expressionOrBoolean". The *ngIf="expressionOrBoolean" directive syntax does not show the value as the page loads. With the latter, the template is expected to be referenced and used elsewhere.
Change Styles On the Fly with ngStyle
The options include bold, italic, and strike-through.
ngStyle Usage
titleStyle, a Variable That Groups Styles for the Superhero Title
HTML Template with ngStyle
Conclusion
This chapter introduced you to directives. It described the types of component directives, structural directives, and attribute directives.
It described the purpose and usage of two Angular elements: ng-template and ng-container.
It lists a few important and often-used directives that help code conditional logic in a template: ∗ngIf and ∗ngSwitch with ∗ngSwitchCase and ∗ngSwitchDefault.
The chapter also described ∗ngForOf, which helps you to iterate through arrays.
Exercise
Abelisauridae
Noasauridae
Megalosauridae
Reference
Angular documentation (https://angular.io/)