How to use ngIf Directive in Angular 9 Applications

  • 2020-03-24 06:20 AM
  • 404

In this Angular 9 tutorial, you'll be learning about how you can use ngIf Directive in your Angular 9 Applications.

What’s the ngIf Directive?

The ngIf directive in Angular allows you to do conditional rendering of template parts i.e you can show or hide an HTML element on your Angular 9 HTML template based on some condition.

Let’s get started started!

See this Stackblitz example of how to use ngFor and ngIf in your Angular HTML template:

Read Also: How to Create Components in Angular 9

ngIf with Angular 9 Example

The ngIf directive can be very useful in scenarios where you want to show a part of your Angular 9 application UI.

Let’s see a simple example.

Let’s suppose, we have the following Angular 9 component that lives in the src/app/contact-list/contact-list.component.ts:

import { Component } from '@angular/core';  
@Component({  
  selector: 'contact-list',  
  templateUrl: './contact-list.component.html',  
  styleUrls: ['./contact-list.component.css']  
})  
export class ContactListComponent {  
  showActions: boolean = false;  
  contacts: <> = [
    {name: "test1", email:"[email protected]"},
    {name: "test2", email:"[email protected]"},
    {name: "test3", email:"[email protected]"},
    {name: "test4", email:"[email protected]"}
    ]
}  

This component will be used to display a table of contacts with various buttons, in each row, that will be used to update or delete the contacts.

Typically, in this kind of applications, you only want to let users to update or delete items if they are logged in and have the required permissions.

This means, that you either need to disable or hide the delete and update buttons if users are not logged in.

Read Also: Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

Using ngIf in Angular 9

One way of achieving this in Angular 9 applications is through using the ngIf directive.

On the ContactListComponent component, we have added the Boolean showActions variable. You can then listen for the authentication state and set the showActions accordingly.

In the component’s template, you need to use the ngIf directive and show or hide the actions’ buttons depending on the value of the showActions variable. This is an example of the template:

<h1>Contact List</h1>
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th *ngIf="showActions">Actions</th>
</thead>
<tbody>
<tr *ngFor="let contact of contacts">
<td>
    {{contact.name}}
</td>
<td>
    {{contact.email}}
</td>
<td *ngIf="showActions">
    <button>Delete</button>
    <button>Update</button>
</td>
</tr>
</tbody>
</table>  

This will only show the table cells that contains the actions buttons when showActions is True.

Read Also: How to Build Progressive Web Apps (PWA) using Angular 9

Conclusion

In this quick tutorial, we learned about the ngIf directive in Angular 9.

Suggest