Angular 7: Built-in Directives

Introduction

Angular provides a number of built-in directives, which are attributes we add to our HTML elements that give us dynamic behavior. In this chapter, we’re going to cover each built-in directive and show you examples of how to use them.

By the end of this chapter you’ll be able to use the basic built-in directives that Angular offers.

How To Use This Chapter

Instead of building an app step-by-step, this chapter is a tour of the built-in directives in Angular. Since we’re early in the book, we won’t explain every detail, but we will provide plenty of example code.

Remember: at any time you can reference the sample code for this chapter to get the complete context.

If you’d like to run the examples in this chapter then see the folder code/built-in-directives and run:

   npm install
   npm start

And then open http://localhost:4200 in your browser.

NgIf

The ngIf directive is used when you want to display or hide an element based on a condition. The condition is determined by the result of the expression that you pass into the directive.

If the result of the expression returns a false value, the element will be removed from the DOM.

Some examples are:

{lang=html,line-numbers=off}
<div *ngIf=”false”></div> <div *ngIf=”a > b”></div> <div *ngIf=”str == ‘yes’”></div> <div *ngIf=”myFunc()”></div>

Note for AngularJS 1.x Users

If you’ve used AngularJS 1.x, you may have used the ngIf directive before. You can think of the Angular version as a direct substitute.

On the other hand, Angular offers no built-in alternative for ng-show. So, if your goal is to just change the CSS visibility of an element, you should look into either the ngStyle or the class directives, described later in this chapter.

NgSwitch

Sometimes you need to render different elements depending on a given condition.

When you run into this situation, you could use ngIf several times like this:

{lang=javascript,line-numbers=off}
<div class="container"> <div *ngIf=”myVar == ‘A’“>Var is A</div> <div *ngIf=”myVar == ‘B’“>Var is B</div> <div *ngIf=”myVar != ‘A’ && myVar != ‘B’“>Var is something else</div> </div>

But as you can see, the scenario where myVar is neither A nor B is verbose when all we’re trying to express is an else.

To illustrate this growth in complexity, say we wanted to handle a new value C.

In order to do that, we’d have to not only add the new element with ngIf, but also change the last case:

{lang=javascript,line-numbers=off}
<div class="container"> <div *ngIf=”myVar == ‘A’“>Var is A</div> <div *ngIf=”myVar == ‘B’“>Var is B</div> <div *ngIf=”myVar == ‘C’“>Var is C</div> <div *ngIf=”myVar != ‘A’ && myVar != ‘B’ && myVar != ‘C’“>Var is something else</div> </div>

For cases like this, Angular introduces the ngSwitch directive.

If you’re familiar with the switch statement then you’ll feel very at home.

The idea behind this directive is the same: allow a single evaluation of an expression, and then display nested elements based on the value that resulted from that evaluation.

Once we have the result then we can:

Let’s rewrite our example using this new set of directives:

{lang=javascript,line-numbers=off}
<div class=”container” [ngSwitch]=”myVar”> <div *ngSwitchCase=”‘A’“>Var is A</div> <div *ngSwitchCase=”‘B’“>Var is B</div> <div *ngSwitchDefault>Var is something else</div> </div>

Then if we want to handle the new value C we insert a single line:

{lang=javascript,line-numbers=off}
<div class=”container” [ngSwitch]=”myVar”> <div *ngSwitchCase=”‘A’“>Var is A</div> <div *ngSwitchCase=”‘B’“>Var is B</div> <div *ngSwitchCase=”‘C’“>Var is C</div> <div *ngSwitchDefault>Var is something else</div> </div>

And we don’t have to touch the default (i.e. fallback) condition.

Having the ngSwitchDefault element is optional. If we leave it out, nothing will be rendered when myVar fails to match any of the expected values.

You can also declare the same *ngSwitchCase value for different elements, so you’re not limited to matching only a single time. Here’s an example:

    <h4 class="ui horizontal divider header">
      Current choice is {{ choice }}
    </h4>
    
    <div class="ui raised segment">
      <ul [ngSwitch]="choice">
        <li *ngSwitchCase="1">First choice</li>
        <li *ngSwitchCase="2">Second choice</li>
        <li *ngSwitchCase="3">Third choice</li>
        <li *ngSwitchCase="4">Fourth choice</li>
        <li *ngSwitchCase="2">Second choice, again</li>
        <li *ngSwitchDefault>Default choice</li>
      </ul>
    </div>
    
    <div style="margin-top: 20px;">
      <button class="ui primary button" (click)="nextChoice()">
        Next choice
      </button>
    </div>

In the example above when the choice is 2, both the second and fifth lis will be rendered.

NgStyle

With the NgStyle directive, you can set a given DOM element CSS properties from Angular expressions.

The simplest way to use this directive is by doing [style.<cssproperty>]="value". For example:

    <div [style.background-color]="'yellow'">
      Uses fixed yellow background
    </div>

This snippet is using the NgStyle directive to set the background-color CSS property to the literal string 'yellow'.

Another way to set fixed values is by using the NgStyle attribute and using key value pairs for each property you want to set, like this:

    <div [ngStyle]="{color: 'white', 'background-color': 'blue'}">
      Uses fixed white text on blue background
    </div>

Notice that in the ng-style specification we have single quotes around background-color but not around color. Why is that? Well, the argument to ng-style is a JavaScript object and color is a valid key, without quotes. With background-color, however, the dash character isn’t allowed in an object key, unless it’s a string so we have to quote it.

Generally I’d leave out quoting as much as possible in object keys and only quote keys when we have to.

Here we are setting both the color and the background-color properties.

But the real power of the NgStyle directive comes with using dynamic values.

In our example, we are defining two input boxes with an apply settings button:

    <div class="ui input">
      <input type="text" name="color" value="{{color}}" #colorinput>
    </div>
    
    <div class="ui input">
      <input type="text" name="fontSize" value="{{fontSize}}" #fontinput>
    </div>
    
    <button class="ui primary button" (click)="apply(colorinput.value, fontinput.value)">
      Apply settings
    </button>
 
This page is a preview of ng-book 2.
Get the rest of this chapter plus hundreds of pages Angular 7 instruction, 5 sample projects, a screencast, and more.

 

Ready to master Angular 7?

  • What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall? Imagine how quickly you could work if you knew the best practices and the best tools?
  • Stop wasting your time searching and have everything you need to be productive in one, well-organized place, with complete examples to get your project up without needing to resort to endless hours of research.
  • You will learn what you need to know to work professionally with ng-book: The Complete Book on Angular 7 or get your money back.
Download the First Chapter (for free)