Class Overview
Selectors
[ngIf]
Class Description
Conditionally includes a template based on the value of an expression
.
ngIf
evaluates the expression
and then renders the then
or else
template in its place
when expression is truthy or falsy respectively. Typically the:
then
template is the inline template ofngIf
unless bound to a different value.else
template is blank unless it is bound.
Most common usage
The most common usage of the ngIf
directive is to conditionally show the inline template as
seen in this example:
Showing an alternative template using else
If it is necessary to display a template when the expression
is falsy use the else
template
binding as shown. Note that the else
binding points to a <ng-template>
labeled #elseBlock
.
The template can be defined anywhere in the component view but is typically placed right after
ngIf
for readability.
Using non-inlined then
template
Usually the then
template is the inlined template of the ngIf
, but it can be changed using
a binding (just like else
). Because then
and else
are bindings, the template references can
change at runtime as shown in this example.
Storing conditional result in a variable
A common pattern is that we need to show a set of properties from the same object. If the
object is undefined, then we have to use the safe-traversal-operator ?.
to guard against
dereferencing a null
value. This is especially the case when waiting on async data such as
when using the async
pipe as shown in folowing example:
There are several inefficiencies in the above example:
- We create multiple subscriptions on
userStream
. One for eachasync
pipe, or two in the example above. - We cannot display an alternative screen while waiting for the data to arrive asynchronously.
- We have to use the safe-traversal-operator
?.
to access properties, which is cumbersome. - We have to place the
async
pipe in parenthesis.
A better way to do this is to use ngIf
and store the result of the condition in a local
variable as shown in the the example below:
Notice that:
- We use only one
async
pipe and hence only one subscription gets created. ngIf
stores the result of theuserStream|async
in the local variableuser
.- The local
user
can then be bound repeatedly in a more efficient way. - No need to use the safe-traversal-operator
?.
to access properties asngIf
will only display the data ifuserStream
returns a value. - We can display an alternative template while waiting for the data.
Syntax
Simple form:
<div *ngIf="condition">...</div>
<div template="ngIf condition">...</div>
<ng-template [ngIf]="condition"><div>...</div></ng-template>
Form with an else block:
Form with a then
and else
block:
Form with storing the value locally:
exported from common/index, defined in common/src/directives/ng_if.ts