Handling Null Values in HTML Templates with Angular
Jun 17, 2020 • 9 Minute Read
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:
- Node - 12.17.0
- Angular CLI - 9.0.2
- 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
- Click on the File menu in the top menu bar and select the menu option Open Folder.
- In the file dialog box, navigate to the folder where you generated the application.
- 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.
- Go to the command prompt and run following command:
cd safenavigation-demo
- Run the following command to install jquery:
npm i jquery
- Run the following command to install Bootstrap:
npm i bootstrap
-
In Visual Studio Code, open the file angular.json.
-
Add the following line in the styles array before src/style.css.
"node_modules/bootstrap/dist/css/bootstrap.min.css",
- Add the following lines in the scripts array:
"node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js"
-
In Visual Studio Code, open the file src > index.html.
-
At line number 10, in the body element, add the following class:
class="container"
The final code should look like this:
<body class="container">
<app-root></app-root>
</body>
Now the project is all set to develop the events page.
Developing the Events Page
- Run the following command in the command prompt:
ng generate component event-thumbnail
- 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.
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;
}
- 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.
<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>
- Run the following command in the command prompt:
ng generate component events-list
- 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.
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()
{
}
}
- 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.
<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>
- 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
-
Run the following command in the command prompt to start and Angular development server in watch mode: ng serve
-
If prompted to share Angular CLI usage data, press the N key to not share it.
-
Open a browser and type the following URL in the address bar to launch the application: https://localhost:4200. You will see the events page.
-
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.
- 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>
- 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
- 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.
<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>
- 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.