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:
Here, debts is a collection with values such as
For each of the items in debts the element li will get rendered.
The output for the above code is
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
gets compiled into this
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
Where myFilter is
We are going to create a directive called ngForIf
Specifying it’s selector
Let’s extend the existing NgFor directive
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.
Creating the setter for it
Implementing our ngDoCheck lifecycle hook and calling the ngDoCheck of ngFor class
Now, To implement the filtering feature, we will create a predicate type for it
Member for storing the filter method
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.
Don’t forget to provide the instances to the super contructor
Now we can use our custom structural directive with a filter like this.
Output using the ngForIf Directive
You can find the source code at given link: https://stackblitz.com/edit/angular-ivy-uoqa3h
Top comments (0)