[ngIf]="condition"
The one at the bottom is used by most developers. It is known as the shorthand syntax.
if(condition) {
It is the same here, we start with the ngIf directive and then a Boolean condition. If it is true, it will add the element to the page and render it onto the screen.
<div *ngIf="...">
You will need to keep in mind that the elements are not being hidden from the view. The elements are being added to the page when the Boolean value is true and they are being removed from the page when it is false.
<div>Hello World</div>
[ngIf]
To begin, add the ngIf directive to the element, and set it to true using the compact syntax. We should see a hello world message.
<div [ngIf]="true">Hello World</div>
Hmmm... There is nothing there. Let’s take a look at console.
<div [ngIf]="true">Hello World</div>
In order for us to use the ngIf directive with the compact syntax, we need to wrap the elements with the ng-template tags and then place the ngIf directive inside the template tag
<ng-template [ngIf]="true">
Save the project and go to the browser.
*ngIf
*ngIf
With this syntax, we can skip the step to wrap our elements with the ng template tags and place the ngIf directive directly inside the element.
<div *ngIf="true">Hello World</div>
Behind the scenes, if Angular sees this syntax, it will automatically wrap the element with the ng template tags so we do not need to do it manually. This is why this is the go-to syntax for most developers.
As you can see, we got the same results.
Else Blocks
<div *ngIf="true">Hello World</div>
Let’s say that we want to display this div element when the condition is false. We need to wrap the element with the ng template tags and then give it a template reference variable using the hash symbol.
<ng-template [ngIf]="true">
Then locate the if statement of the directive and tell it which template to render when it is false. Put "else" and then the template we want to use.
<div *ngIf="true else template2">Hello World</div>
There is no shorthand syntax for the else block so we must wrap our elements with the ng template tags.
<div *ngIf="false else template2">Hello World</div>
Save the project and go to the browser.
As you can see, it is using the template from the else block.
Recap
Error Handling
Sometimes you may get a binding error - "Can't bind to "ngIf" since it's not a known property." To fix this, check if the component is added to the "declarations" section of the app module.