Angular nglf


In this blog we will explore how to use ngIf with “Else” statement and “Then”.

Angular ngIf:

Even Though HTML is a programming language, it doesn’t have an if statement like Javascript. The Angular ngIf directive will work essentially as an if statement for HTML.

Example:

In the above example, the container div will only be shown to the logged-in user, otherwise, the whole content of the div will be invisible.

The button inside the container will be visible only if the user is an administrator.

If there is no container available for the section that we want to hide or show, we can use the ng-container as a directive instead of creating a div merely to apply ngIf. This will show or hide content without creating an extra div.

Hiding elements using CSS:

There are ways to show or hide content with just plain css by using display and visible attributes. We can add or remove these css attributes using javascript to hide an element from the page. But this will not be the same as ngIf

With ngIf, if we hide an element, then that element does not exist on the page, meaning if we inspect the page using chrome dev tools, you won’t find any HTML element present in the DOM. Instead you will find a strange-looking element like below, if you apply ngIf directive:

The above comments are just for debugging purposes. It helps us in identifying the position of missing elements.

If we use display or visibility CSS properties, the HTML element will be hidden in the page, but when we inspect using chrome dev tools the elements will be visible in DOM .

Along with booleans, we can also pass strings, arrays, objects, and more. 

ngIf else: 

Just like if-else statements in javascript, we also have else in ngIf.

Else part will point to template reference. If emp.length condition is false, then #noEmp template will be initiated and applied to the page, right where ngIf directive was applied. If emp.length is true, then noEmp template will never be initiated and won’t be present in the page. 

ngIf then else : 

The Angular ngIf will also support if-then-else syntax like javascript.

In the above example, ngIf is applied to an ng-container directive. Either one of the two templates empList or noEmp is going to be initiated, depending on the truthiness of emp.length expression. Like Javascript, this syntax does not support multiple if-else statements, but we can implement equivalent functionality using ngSwitch.

Leave A Comment

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