The next step I am taking in learning Angular: understanding
I will cover how
ngIf differs from using
ngStyle under the hood in
the inspector. I also go through how Angular keeps track of
the DOM using
ng-reflect-ng-if by walking through an interactive
example and displaying changes in the inspector.
ngIf works gives another tool to conditionally display
items in the page and modifying the DOM.
This article will take about four minutes to read.
ngStyle can make items invisible on a page.
The template code:
The component code:
When digging through the page through the browser’s inspector, this shows up:
Double clicking on
hidden and changing the value to
automatically reveals the image!
Depending on the use case, this can be fine or it cannot be.
In situations where hidden items are still discover-able through the
HTML source, using
ngStyle won’t help you.
attributes in the DOM. The item is there, only set to
ngStyle is an attribute
directive, a directive
that modifies DOM attributes.
To make the item harder to discover, Angular has structural directives , that modify the structure of the DOM so only things that should be there are there.
Let’s start with
ngIf - it’s a directive that modifies the
structure of the DOM based on a boolean condition. When the boolean
condition is true, the DOM element will appear. When the condition is
false, the DOM element will not appear.
ngIf’s format is:
An example template that uses
When inspecting the HTML source, the element shows:
*ngIf="false", Angular doesn’t display the paragraph:
appear in the DOM, even in the inspector. This is a way to hide
elements, even in the HTML source.
ngIf to work, Angular needs to keep track of where to insert the
element when the condition is true, it includes special elements:
To keep track of where in the DOM these elements should be if the state changes.
Interactive Testing Out
Let’s modify the program from a previous version, adding an input box that will display an image when the word matches:
and the associated component code:
When you type
ngIf in the input field, show the “Display if ngIf is
typed in” paragraph.
Let’s see what is happening in the inspector when the input changes:
show_ngIf changes from
true, Angular makes
structural changes to the DOM, inserting the appropriate element at
Let’s modify the code to show the dog image when entering
dog in the
input field and hide it when
dog is not entered.
The associated component code:
and what’s going on in the inspector:
ngIf is magical~!
When an element needs appear on the page after a certain condition,
even in the source, using a structural directive such as
make that happen.
Angular has special hooks to maintain where in the DOM the
should modify using
ng-reflect-ng-if elements, that’s part of the