Angular NgIf Else Then – NgIf with Observables and Async Pipe (Angular 6)

In the tutorial, we show how to use Angular NgIf directive to add or remove an element from the DOM by evaluating the expression and then renders the then or else template.

Related posts:
Angular 6 – NgFor Repeater Directive – Loop over a Collection

Technologies

  • Node.js – version v10.4.0
  • Angular – version 6
  • Visual Studio Code – version 1.24.0

Angular NgIf

Preparation

We create an Angular 6 project as below structure:

angular-6-ngif + project-structure

– Generate Angular Project:

angular-6-ngif + create-angular-6-project

– Generate NgIfComponent :

angular-6-ngif + create-ng-if-component

– Now, add selector tag app-ng-if of NgIf component to app.component.html.

NgIf Common Usage

Syntax:

Practice :

-> Modify NgIfComponent class as below:

-> result:

angular-6-ngif + ngif-common-case

We got the same result if using [ngIf] syntax:

If we change show:boolean = false then Angular will not render the text: ‘Text to show ‘.

NgIf Else

Angular provides the else statement to control the render flow inside a component’s template.

Syntax:

Practice:

-> Modify NgIfComponent class as below:

– When show = true , result:

angular-6-ngif + ngif-common-case

– When show = false, result:

angular-6-ngif + ngif-else-statement

We also can achieve above result with [ngIfElse] syntax:

NgIf Then Else

Angular provides then statement that helps move initial *ngIf template, to outside of the binding element.

-> Syntax:

Practice:

-> Modify NgIfComponent class as below:

– When show = true , result:

angular-6-ngif + ngif-common-case

– When show = false, result:

angular-6-ngif + ngif-else-statement

We also can achieve above result with [ngIfThen] syntax:

NgIf with Observables and Async
Storing Value Locally

Syntax:

Practice:

-> Modify NgIfComponent class as below:

-> Result:

angular-6-ngif + store-value-locally

NgIf with Observables and Async

SourceCode

How to run the below sourcecode:

-> Source Code:

Angular-6-NgIF

By grokonez | June 20, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*