*ngIf in angular

What is *ngIf?

*ngIf is directive in angular. You can show or hide the HTML element by using *ngIf based on condition. If the condition is true, then the HTML element gets shown by ngIf otherwise it is hidden.

Syntax:

*ngIf="condition"

here, you have to pass condition as expression to the *ngIf directive.

Example:

Create property or variable in component and set its value to true like shown in the following code

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  showElement = false;
}

Use *ngIf and assign showElement to it. As the value of showElement is true, the HTML element will be shown.

<h1 *ngIf="showElement">Display this only if showElement property value is true.</h1>

Using logical operator:

You can use logical operators like !, && and || for setting condition for *ngIf.

ngIf-else:

You can set else condition to HTML element using *ngIf directive as following. else block will only be shown if the condition given for *ngIf is false. Note that, else block has to inside ng-template tag. You have to assign a reference ID after the *ngIf condition and then use it in the ng-template tag.

See the following code:

<h1 *ngIf="showElement; else hide">Display this only if showElement property value is true.</h1>

<ng-template #hide>
  <h1>Display this if showElement property value is false.</h1>
</ng-template>

As the value of showElement is true, the if block will be shown. If showElement value is false, then else block will get shown.

Conclusion:

In this article, you learned how to use *ngIf and ngIf-else in angular. You also learned how to apply else block to the *ngIf condition. If you have problems while implementing or understanding code, you can ask me through the comment section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments