ngIf else in angular

In this article, you will learn how to use ngIf else. You have to use else block after using *ngIf directive. If you don’t know how to use *ngIf then refer to the following article:
*ngIf in angular

You can set else condition to HTML element using *ngIf directive. else block will only be shown if the condition given for *ngIf is false. Note that, else block has to be 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 of component and HTML file.

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

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

You learned how to use ngIf else condition. If you have problems while implementing code, you can ask me through the comment section.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments