Angular 6|7 ngIf by Example

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

Throughout this quick tutorial, you'll be learning about how you can use ngIf in your Angular 6 applications.

ngIf by example

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

Let's see a simple example.

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

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

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 for users are not logged in.

One way of achieving this in Angular 6 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. This is an example of the template:

<h1>Contact List</h1>
<th *ngIf="showActions">Actions</th>
<tr *ngFor="let contact of contacts">
<td *ngIf="showActions">

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

comments powered by Disqus