Author avatar

Parul Saxena

Handling Null Values in HTML Templates with Angular

Parul Saxena

  • Jun 17, 2020
  • 9 Min read
  • 2,979 Views
  • Jun 17, 2020
  • 9 Min read
  • 2,979 Views
Languages Frameworks and Tools
Front End Web Developer
Client-side Frameworks
Angular

Introduction

Null or undefined values are never in your control when your app is talking to in-house developed APIs or third-party APIs. So when null or undefined values do occur in your data, your app should handle them gracefully. Your user experience should not look obscure. Thankfully, there is out-of-the-box (OOB) capability in Angular to handle null or undefined data called the safe navigation operator.

In this guide, we will take a look at how to use the safe navigation operator with the help of a real-world scenario: creating a small page that will render thumbnails of technical events on any website (e.g., Pluralsight.com).

To implement the steps in this guide, you must have the following:

  1. Node - 12.17.0
  2. Angular CLI - 9.0.2
  3. Visual Studio Code - 1.45.1

Creating and Setting Up the Project

Execute the following command to create an Angular project.

ng new safenavigation-demo

Opening the Generated Application in Visual Studio Code

  1. Click on the File menu in the top menu bar and select the menu option Open Folder.
  2. In the file dialog box, navigate to the folder where you generated the application.
  3. In this folder, you should see a folder named safenavigation-demo. Select this folder and click Open in the file dialog box.

Setting up the Project

We will install Twitter Bootstrap and jQuery and refer them in our project to use Bootstrap styles to improve user experience.

  1. Go to the command prompt and run following command:

cd safenavigation-demo

  1. Run the following command to install jquery:

npm i jquery

  1. Run the following command to install Bootstrap:

npm i bootstrap

  1. In Visual Studio Code, open the file angular.json.

  2. Add the following line in the styles array before src/style.css.

"node_modules/bootstrap/dist/css/bootstrap.min.css",

  1. Add the following lines in the scripts array:

"node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js"

  1. In Visual Studio Code, open the file src > index.html.

  2. At line number 10, in the body element, add the following class:

class="container"

The final code should look like this:

1
2
3
<body class="container">
  <app-root></app-root>
</body>

Now the project is all set to develop the events page.

Developing the Events Page

  1. Run the following command in the command prompt:

ng generate component event-thumbnail

  1. In Visual Studio Code, open the file src > app > event-thumbnail > event-thumbnail.component.ts, delete the contents of the file, and add following code. This code defines the event thumbnail component and adds an input property to it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector:'app-event-thumbnail',
    templateUrl:'./event-thumbnail.component.html',
    styles:[`
        .green { color:#003300 !important; }
        .bold { font-weight:bold; }
        .thumbnail { min-height: 210px; padding-left: 10px; background-color:#343a40; margin-bottom:10px; }
        .pad-left { margin-left: 10px; }
        .well div { color: #bbb; }
        `]
})
export class EventThumbnailComponent
{
    @Input() event:any;
}
  1. In Visual Studio Code, open the file src > app > event-thumbnail > event-thumbnail.component.html, delete the contents of the file, and add following code. This code is the HTML template for the event thumbnail component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="well hoverwell thumbnail">
    <h2>{{event.name | uppercase}}</h2>
    <div>Date: {{event.date | date}}</div>
    <div>Time: {{event.time}}</div>
    <div [ngSwitch]="event.time">
        <span *ngSwitchCase="'8:00 am'">Early Start</span>
        <span *ngSwitchCase="'10:00 am'">Late Start</span>
        <span *ngSwitchDefault>Normal Start</span>
    </div>
    <div>Price: {{event.price | currency}}</div>
    <div>
        <span>Online URL: {{ event.onlineUrl }}</span>
    </div>
</div>
  1. Run the following command in the command prompt:

ng generate component events-list

  1. In Visual Studio Code, open the file src > app > events-list > event-list.component.ts, delete the contents of the file, and add following code. This code defines the event list component and events data that will render in the event thumbnail component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-events-list',
    templateUrl: './events-list.component.html'
})
export class EventsListComponent implements OnInit
{
    events = [
        {
            name:'Ng-Europe',
            date:'09/10/2020',
            time:'8:00 am',
            price:'200',
            onlineUrl:'https://www.pluralsight.com/angular/ng-europe'
        },
        {
            name:'Angular Fundamentals',
            date:'09/10/2020',
            time:'8:00 am',
            price:'200',
            onlineUrl:'https://www.pluralsight.com/angular/ng-fundamentals'
        },
        {
            name:'Ng-India',
            date:'09/10/2020',
            time:'9:00 am',
            price:'2000',
            onlineUrl:'https://www.pluralsight.com/angular/ng-india'
        },
        {
            name:'Angular - Zero to Hero',
            date:'09/10/2020',
            time:'10:00 am',
            price:'200',
            onlineUrl:'https://www.pluralsight.com/angular/ng-europe'
        }
    ];
    constructor(){
        
    }

    ngOnInit()
    {
        
    }
}
  1. In Visual Studio Code, open the file src > app > events-list > event-list.component.html, delete the contents of the file, and add following code. This code defines the HTML template for the events list component.
1
2
3
4
5
6
7
8
9
<div>
    <h1>Upcoming Angular Events</h1>
    <hr />
    <div class="row">
        <div class="col-md-5" *ngFor="let event of events">
            <app-event-thumbnail [event]="event"></app-event-thumbnail>
        </div>
    </div>
</div>
  1. In Visual Studio Code, open the file src > app > app.component.html, delete the contents of the file, and add the following code. This code will use the events list component in the app component. <app-events-list></app-events-list>

Launching the Development Server

  1. Run the following command in the command prompt to start and Angular development server in watch mode: ng serve

  2. If prompted to share Angular CLI usage data, press the N key to not share it.

  3. Open a browser and type the following URL in the address bar to launch the application: http://localhost:4200. You will see the events page.
  4. Notice that the thumbnails are rendering fine with all the data.

Mimicking the Null or Undefined Data

Now let's mimic a situation where we get null or undefined data.

  1. In Visual Studio Code, open the file src > app > events-list > event-list.component.html and at line number 6, edit the event-thumbnail element so that it looks like this:

    <app-event-thumbnail [event]=""></app-event-thumbnail>

  2. If you go back to the browser and look at the thumbnails now, they will be rendering empty boxes without any values. They look fine, but if you look at the console in the developer toolbar, you will notice there are many exceptions. So let's handle that using the safe navigation operator.

Handling Null or Undefined Data

  1. In Visual Studio Code, open the file src > app > event-thumbnail > event-thumbnail.component.html, delete the contents of the file, and add following code. Notice that we have added a safe navigation operator to the event input property to handle a case where it is null or undefined.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="well hoverwell thumbnail">
    <h2>{{event?.name | uppercase}}</h2>
    <div>Date: {{event?.date | date}}</div>
    <div>Time: {{event?.time}}</div>
    <div [ngSwitch]="event?.time">
        <span *ngSwitchCase="'8:00 am'">Early Start</span>
        <span *ngSwitchCase="'10:00 am'">Late Start</span>
        <span *ngSwitchDefault>Normal Start</span>
    </div>
    <div>Price: {{event?.price | currency}}</div>
    <div>
        <span>Online URL: {{ event?.onlineUrl }}</span>
    </div>
</div>
  1. Go back to the browser and notice that the application is now rendering empty boxes with labels. If you open the developer toolbar, you will notice that there are no exceptions in the console. This is the desired state.

Conclusion

Congratulations!! You have handled null or undefined data using the safe navigation operator in Angular. For more information, please refer to Safe Navigation Operator in Angular.

1