In Angular, the *ngIf directive is used to conditionally include a template based on the value of an expression. While it’s common to use *ngIf for simple conditional rendering, there are scenarios where you need to render different templates based on the same condition. This is where *ngIf with else comes into play.
Basic ngIf Usage
Before diving into using *ngIf with else, let’s cover the basic usage of *ngIf. You can use it to include a template if an expression evaluates to true:
<div *ngIf="isValid">
Content here ...
</div>
In this example, the <div> element will only be included in the DOM if isValid is true.
Using ngIf with Else
To render different templates based on the same condition, you can use *ngIf with else. The syntax involves specifying an else clause followed by a template reference variable:
<div *ngIf="isValid; else other_content">
Content here ...
</div>
<ng-template #other_content>
Other content here...
</ng-template>
In this example, if isValid is true, the first <div> will be rendered. If isValid is false, the template referenced by #other_content will be rendered instead.
Using ngIf with Then and Else
Angular also supports using *ngIf with both then and else. The syntax involves specifying a then clause followed by an else clause, each referencing a different template:
<div *ngIf="isValid; then content else other_content">
This content is never shown
</div>
<ng-template #content>
Content here ...
</ng-template>
<ng-template #other_content>
Other content here...
</ng-template>
In this case, if isValid is true, the template referenced by #content will be rendered. If isValid is false, the template referenced by #other_content will be rendered.
Control Flow Syntax (Angular 17 and Higher)
As of Angular 17, a new control flow syntax has been introduced that allows for cleaner and more expressive conditional logic directly in templates. This includes support for @if, @else if, and @else:
@if (a > b) {
{{a}} is greater than {{b}}
} @else if (b > a) {
{{a}} is less than {{b}}
} @else {
{{a}} is equal to {{b}}
}
This syntax simplifies conditional logic and improves readability in your templates.
Best Practices
When using *ngIf with else, keep the following best practices in mind:
- Always define the template reference variable (
#templateName) for theelseclause. - Use meaningful names for your template reference variables to improve code readability.
- Consider using the new control flow syntax if you’re working with Angular 17 or higher.
By mastering the use of *ngIf with else, you can create more dynamic and responsive templates in your Angular applications, enhancing user experience and simplifying your codebase.