

Let’s take an empty component and a simple Boolean value of true:

There are four main ways we can use ngIf, so let’s start by exploring the most basic use case. We’ll also cover why we use the asterisk syntax, shortly. 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.Īngular will simply add or remove your DOM nodes, mount or remount your components as the expression changes (if it ever does, that’s up to you). The syntax for NgIf is nice and simple, we can declare it on an element, or component, and let it work its magic. Let’s explore the ins and outs of ngIf, and how we can utilise (the right way) in our Angular apps. This conditional would be evaluated similarly to how JavaScript would evaluate an if (condition) statement, converting the value you supply to a truthy or falsy value and progressing accordingly. NgIf is a behavioral directive that allows us to toggle part of a template based on a conditional value. To learn more, visit JavaScript switch.Before we dive in too deep, let’s learn the concepts behind NgIf and why it exists. If you need to make a choice between more than one alternatives based on a given test condition, the switch statement can be used. To learn more, visit JavaScript Ternary Operator. In certain situations, a ternary operator can replace an if.else statement. For example, you can replace const number = 2 Ĭonsole.log("The number is negative or zero.") The syntax of the if statement is: if (condition) in our programs. In JavaScript, there are three forms of the if.else statement. In such situations, you can use the JavaScript if.else statement to create a program that can make decisions. For example, assigning grades A, B or C based on marks obtained by a student. In computer programming, there may arise situations where you have to run a block of code among more than one alternatives.
