The ins and outs of Angular-*ngIf!

This is my first post in a series called “The in and outs of Angular”. Today we will talk about the structural directive *ngIf

Although we all know how to use ngIf/[ngIf] lets take a second to go over Angular’s definition of it,
A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean.*”
So in basic terms ngIf is a simple directive that will **render **in run time by the condition value. So how does this work in actual run time ?


A basic implementation of ngIf

ngIf is actually a setter (link). once a new value is emitted into the setter it will go into action to check if it needs to render the html element or not, by using a setter instead of ngOnChanges angular gets a more precise and less prone to buggy code. only running functionality once the value of ngIf condition changes .

once a new value is emitted to ngIf to will run the _updateView function

In the ngIf directive the most important function is the _updateView()
Every @Input() will emit that function. so how does ngIf decide to render the html ?

if the condition is a truthy value (!!value) it will first clear any existing code in the view and if there is a template to render it will render it, see diagram below for a more visual explanation of the code above

When ngIf decides to render our html it uses the **ViewContainerRef **which represents a container that can have multiple components attached to it and has knowledge of where it is in the DOM tree (this is why it renders it in the correct place and not randomly on the page ).
A ViewContainerRef’s createEmbeddedView function will take the relevant template and the context of the ngIf as parameters and will render the template/code to the required space and place in the page. and obviously run throughout its component life cycle if needed.


Things to note:

  1. if no specific template given for the ngIf it will use the code block it’s been placed on.

    hello world

ngIf will use the div element as the template (this is how we usually use it )

  1. you can explicitly use 2 different templates, one for then and the other for the else

When using a template for the then value of ngIf, it will assert that it is a valid template, and will throw and error if it is not.

  1. Each time a class component is rendered as in a result of the ngIf condition it will reset it self and run the component life cycles such as onInit. so make sure you do not have memory leaks.