Javascript required
Skip to content Skip to sidebar Skip to footer

Ngif Checks Again Only if Re Routed

Permit'south look at the NgIf directive in this tutorial and uncover how to use it. We'll also explore using NgIf with the "Else" argument and "And so", to give you a total guide on how to use information technology.

You will learn how to testify and hide DOM content based on your data, which we can and so let NgIf handle and render updates to the DOM for us!

What is NgIf?

Before nosotros dive in besides deep, let's learn the concepts behind NgIf and why it exists for us to apply.

JavaScript Array Methods eBook Cover

🎉 Download it free!

Ready to become across ForEach? Get confident with avant-garde methods - Reduce, Notice, Filter, Every, Some and Map.

Equally an extra bonus, we'll as well send you some extra goodies across a few actress emails.

NgIf is a behavioral directive that allows u.s. to toggle a template based on a conditional statement.

This conditional statement would be evaluated similar to how our JavaScript would evaluate an if (status) {} statement, converting the value you supply to a truthy or falsy value and rendering accordingly.

Let's explore the ins and outs of ngIf, and how we can utilise (the right manner) in our Angular apps.

Using Athwart's NgIf

The syntax for NgIf is nice and elementary, we simply tin declare it on an element, or component, and let it work its magic.

Placing the ngIf directive on a component, or element, will in fact hide or show that element based on the expression you pass it to be evaluated.

Angular will simply add or remove your DOM nodes, mount or remount your components equally the expression changes (if information technology ever does, that's upwards to you).

Nosotros'll also cover why we use the asterisk syntax, shortly.

Standard *ngIf in Angular

At that place are four main ways we tin can use ngIf, so let's beginning by exploring the most basic use example.

Let'south accept an empty component and a simple Boolean value of truthful:

                          @              Component              ({              selector              :              '              app-component              '              ,              template              :              `     <div>       Welcome back!     </div>   `              ,              })              export              course              AppComponent              {              isLoggedIn              =              truthful              ;              }                      

We tin can besides use JavaScript-like expressions to achieve a final truthy/falsy value to supply to ngIf - also as composing through multiple variables through various operators.

The bones syntax of the ngIf directive is simple and constructive, all we demand to do is prefix the directive name with an asterisk (*) and add it anywhere inside our template:

                          <!-- negated variable to achieve "if not" -->              <div              *ngIf=              "!isLoggedIn"              >              Delight login, friend.              </div>              <!-- logic && operator -->              <div              *ngIf=              "isLoggedIn && !isNewUser"              >              Welcome back, friend.              </div>              <!-- logic OR operator -->              <div              *ngIf=              "isLoggedIn || isNewUser"              >              Welcome!              </div>                      

Just a few examples, but I'g sure you tin see how easy and make clean it is to utilise ngIf. Note that the ngIf used is a lowercase "n" when declared on an element or component.

Let's move onto some more interesting examples!

*ngIf and Else

I fantastic addition in Angular is the "else" argument. It behaves very like to a JavaScript if (condition) { } else { } statement. Overnice and unproblematic!

Here's how we can use the "else" statement, to command the render flow inside a component'south template:

                          <div              *ngIf=              "isLoggedIn; else loggedOut"              >              Welcome dorsum, friend.              </div>              <ng-template              #loggedOut              >              Please friend, login.              </ng-template>                      

Woah, what'due south this whole #loggedOut syntax? That's a template variable. You can proper noun template variables as you wish.

Using a template variable means that we can create a reference to a specific template role then use it elsewhere - in this example we're supplying it equally an "else" value to ngIf.

We apply the <ng-template> because much like it's HTML5 counterpart <template>, it's also considered "virtual".

Being "virtual" means the <ng-template> contents won't really exist in the compiled DOM, until information technology's needed (you will never see it until Angular renders it).

When it'due south needed (for example the "else" expression kicks into play), Angular volition take hold of the contents of the <ng-template> tag, and supersede the *ngIf contents with it. That'due south it.

So, before we continue, where does this * asterisk come up from? Allow'south learn some more advanced topics and concepts about Angular and its templating engine.

ngIf and ng-template

If you've not notwithstanding explored the <ng-template> syntax of NgIf, then you lot're near to acquire some amazing new skills. It'south all almost sugar syntax. When we practise this:

                          <div              *ngIf=              "isLoggedIn"              >              Welcome back, friend.              </div>                      

What'south actually happening is something like this:

                          <ng-template              [ngIf]=              "isLoggedIn"              >              <div>              Welcome back, friend.              </div>              </ng-template>                      

That's quite a leap if yous've never seen it before, or perhaps saw it in the documentation in one case and quickly closed the page.

In essence, Athwart volition catechumen our *ngIf syntax across to the to a higher place internally. This tells united states of america more well-nigh what'southward happening with [ngIf], which is the directive being bound with a property binding syntax (square brackets []).

Yeah, this does mean, we can supply ngIf, ngIfElse (and ngIfThen) the aforementioned way:

                          <ng-template              [ngIf]=              "isLoggedIn"              [ngIfElse]=              "loggedOut"              >              <div>              Welcome back, friend.              </div>              </ng-template>              <ng-template              #loggedOut              >              <div>              Please friend, login.              </div>              </ng-template>                      

But let's not skip too far ahead, nosotros've not covered ngIfThen merely even so…

*ngIf, Then and Else

Let's learn about the "then" syntax with NgIf.

Adopting the and so syntax alongside ngIf ways we can make clean up our templates a footling and make them a flake more "divide", this promotes clean code and a nice pattern to work with.

Using the "then" syntax also creates more flexibility in some use cases, where nosotros can dynamically change the template reference to and then - essentially swapping <ng-template> on the fly (a less common apply example however).

Yous could optionally adopt this approach to create a more descriptive if/then/else cake. Again, this comes downwardly to use cases and preferences for what (could be) more advanced use cases:

                          <ng-container              *ngIf=              "isLoggedIn; then loggedIn; else loggedOut"              >              </ng-container>              <ng-template              #loggedIn              >              <div>              Welcome back, friend.              </div>              </ng-template>              <ng-template              #loggedOut              >              <div>              Please friend, login.              </div>              </ng-template>                      

Thinking more about our JavaScript, this syntax aligns more with thinking in the flow of ternary statements.

Our thinking above could exist converted to:

            ngIf = expression ? then : else;                      

You'll annotation that "expression" is never used, it is only there to tell the JavaScript runtime which value to render. The same applies with the ng-container example I've used above - which would mean we don't return a DOM node until our NgIf expression is evaluated and later on rendered.

NgIf or [subconscious]?

It'due south interesting to annotation that even though NgIf "hides" our content, information technology actually gets completely destroyed by Athwart whenever it needs to return or remove the template or component we bind it to.

If we'd like our content to nonetheless be visible in the DOM, however remain hidden, and so we should introduce the hidden attribute:

                          <div              [subconscious]=              "!isLoggedIn"              >              Welcome dorsum, friend.              </div>                      

This would then allow Angular to add a hidden aspect if the isLoggedIn property was true - we can prove the nice message!

You'll note hither that I've negated the expression past using the non (!) operator inside the expression.

Yous could say the subconscious attribute is a more sophisticated style="display: none;".

If something is marked subconscious, it is hidden from all presentations, including, for case, screen readers. Read more on MDN about hidden.

*ngIf, Observables and Async Pipe

Some other fantastic addition to ngIf, the async pipe "as" syntax . Learn about this over here in my side by side post. You'll learn how to utilize Observables aslope your new found NgIf knowledge.

JavaScript Array Methods eBook Cover

🎉 Download it free!

Set to go beyond ForEach? Get confident with advanced methods - Reduce, Find, Filter, Every, Some and Map.

As an extra bonus, we'll also send you some extra goodies across a few extra emails.

To learn more than techniques, best practices and real-world skillful noesis, I'd highly recommend checking out my Angular courses - they will guide you lot through your journeying to mastering Angular to the fullest!

Ngif Checks Again Only if Re Routed

Source: https://ultimatecourses.com/blog/angular-ngif-else-then