DEV Community

Cover image for Custom Structural Directives in Angular
devashishSarmah
devashishSarmah

Posted on

Custom Structural Directives in Angular

Custom Structural Directives in Angular

In Angular, Structural directives are the directives that can manipulate the DOM. There are a few built-in structural directives that developers uses in almost every angular applications such as *ngIf, *ngFor, *ngTemplateOutlet, etc.

It’s really amazing how the built-in directives works underneath.

The ngFor Structural Directive

The ngFor structural directive takes a iterable collection and renders a template each iteration. The template is the element that the directive is applied on.

For example:

*ngFor example

Here, debts is a collection with values such as

debt collection

For each of the items in debts the element li will get rendered.

The output for the above code is

Output intial

So, What happens underneath the compilation of ngFor?

A structural directive encloses the element inside a template fragment and the template fragment into a viewContainer.

The statement

ngFor debts statement

gets compiled into this

ngFor debt compiled statement

In simple terms, The ngFor directive gets the collection and renders the templates with specifying their each context.
Each context contains index, $implicit(the particular value of the collection item) and a few other values.

Let’s modify the ngFor directive

Let’s extend the ngFor directive and develope another feature which is filtering.

We want to do something like this

filter feature in the directive

Where myFilter is

myFilter method

We are going to create a directive called ngForIf

Specifying it’s selector

directive selector

Let’s extend the existing NgFor directive

ngForOfIf member

We need to create our own alternative of ngForOf member. Where we’ll store the iterable collection and use it for filtering. As the _ngForOf member from the NgFor class is private, We can only set a value to it.

_ngFor alternative member

Creating the setter for it

_ngForIfOf setter

Implementing our ngDoCheck lifecycle hook and calling the ngDoCheck of ngFor class

ngDoCheck lifecycle hook

Now, To implement the filtering feature, we will create a predicate type for it

predicate type for filter

Member for storing the filter method

filter member variable

And finally the setter for the filter. Here, we are checking the availability for _ngForIfOf reference and assigning the filtered values to the ngFor setter of NgFor class.

filter setter

Don’t forget to provide the instances to the super contructor

constructor

Now we can use our custom structural directive with a filter like this.

template file with custom directive

Output using the ngForIf Directive

Output after filtering feature

You can find the source code at given link: https://stackblitz.com/edit/angular-ivy-uoqa3h

Top comments (0)