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 ?
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 .
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:
if no specific template given for the ngIf it will use the code block it’s been placed on.
ngIf will use the div element as the template (this is how we usually use it )