DEV Community

Cover image for Angular NgIf directive implementation
Dimakatso
Dimakatso

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">
  Loading...
</div>


Enter fullscreen mode Exit fullscreen mode

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

Implementation

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 {
Directive, 
Input, 
TemplateRef, 
ViewContainerRef
} from '@angular/core';

@Directive({
  selector: '[appMyNgIf]'
})
export class MyNgIfDirective {

  @Input() set appMyNgIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

  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';

@Component({
  selector: 'app-root',
  template: `
    <div *appMyNgIf=condition>
      Loading...
    </div>
    <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)