DEV Community

Cover image for Angular NgIf directive implementation

Posted on


Angular NgIf directive implementation

In this article, we will learn how to implememt NgIF structural directive using angular 9.

NgIf directive overview

NgIf — change the DOM layout by adding and removing DOM elements based on a conditional statement. Placing the ngIf directive on a component, or element, will in fact hide or show that element based on the truthy or falsy of the condition you pass it.

NgIf usage example

Using NgIf directive is very simple, all you need to do is add it to any html element that you want to show/hide.

<div *ngIf="isLoading">
Enter fullscreen mode Exit fullscreen mode

The div above will be added to the DOM only if isLoading is true.


Now that we understand NgIf and how to use it, lets start with our own implementation. We'll call it MyNgIf.

Create project using angular CLI

Open terminal and run ng new ngif-directive, this creates new angular project called ngif-directive.

Directive using angular CLI

cd into the project and run ng g d myNgIf to generate directive template file. Open my-ng-if.directive.ts and paste the following code:

import {
} from '@angular/core';

  selector: '[appMyNgIf]'
export class MyNgIfDirective {

  @Input() set appMyNgIf(condition: boolean) {
    if (condition) {
    } else {

  constructor(private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef) { }

Enter fullscreen mode Exit fullscreen mode

The @Directive decorator is used to configure this class as an directive. The brackets ([]) on selector: '[appMyNgIf]' make this directive an attribute selector. Angular will locates each element in the template that has an attribute 'appMyNgIf' and applies the logic of this directive.

The @Input decorator is used to pass data to the directive from the element our directive is attached to.

TemplateRef represent the element our directive is attached.

ViewContainerRef is a container where one or more template can be attached by calling createEmbeddedView method. To remove attached template(s) we call clear method.

Use appMyNgIf directive

Paste the following code into app.component.ts

import { Component } from '@angular/core';

  selector: 'app-root',
  template: `
    <div *appMyNgIf=condition>
    <button (click)="condition = !condition">Show/Hide</button>
export class AppComponent {
  condition = true;
Enter fullscreen mode Exit fullscreen mode

If you run the app (npm start) and go to http://localhost:4200, the div with loading... should be rendered.

Alt Text

If you click Show/Hide button, the div should be hidden.

Alt Text

Code available on github

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post