In this article we'll see how to use @if template syntax in Angular with examples.
@if in Angular
The @if built-in control flow block was introduced in Angular 17, which allows you to conditionally render in Angular templates based on whether the condition is true or false.
This new @if syntax is more concise and intuitive and closer to if-else statement in Javascript. Thus, it is a better alternative than the traditional *ngIf directive in Angular.
With @if, there is also support for @else if and @else statements making the syntax for the full @if block as given below-
@if (condition) {
<!-- Content to display if the condition is true -->
} @else if (anotherCondition) {
<!-- Content to display if anotherCondition is true and the first condition is false -->
} @else {
<!-- Content to display if all preceding conditions are false -->
}
With @if block there is a conditional expression. If the condition evaluates to true, the content within the @if block is rendered in the DOM.
If the condition is false, Angular checks for an @else if block. If an @else if block exists and its anotherCondition is true, its content is rendered.
If @if and @else if (which can occur multiple times) conditions are false, the content within the @else block (if present) is rendered.
If there is only @if block and no @else or @else if blocks are present, the content within the @if block is removed from the DOM, if the condition given with @if is false.
Note that, if you are using *ngIf with standalone component then you need to import either NgIf or CommoModule, whereas @if is a part of the template engine itself, which means it is directly available for use without any explicit imports, which is also an advantage of using @if block in Angular.
@if in Angular example
1. Following example uses @if with @else to show different messages based on whether the loggedIn property is true or false.
import { Component } from '@angular/core';
@Component({
selector: 'app-ifdemo',
standalone: true,
template: `
@if(loggedIn){
<p>Welcome back</p>
}@else {
<p>Please log in</p>
}`,
})
export class IfdemoComponent {
loggedIn: boolean = true;
}
2. Here is another example which uses @if, @else if and @else in Angular.
import { Component } from '@angular/core';
@Component({
selector: 'app-ifdemo',
standalone: true,
template: `
@if(a > b){
<p>{{a}} is greater than {{b}}</p>
}@else if(b > a){
<p>{{b}} is greater than {{a}}</p>
}@else {
<p>{{b}} and {{a}} are equal</p>
}`,
})
export class IfdemoComponent {
a = 22;
b = 20;
}
That's all for this topic @if in Angular With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Angular Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment