Angular ngif else example

Sunny Kushwaha

Admin

Angular ngif else example

In Angular, the ngIf directive is used to conditionally render HTML elements based on a Boolean expression. The ngIf directive can also have an else clause that specifies what to render when the condition is false.

                                    
                                        <div *ngIf="isUserLoggedIn; else guest">
                                            <!-- Your code -->
                                        </div>

                                        <ng-template #guest>
                                            <!-- Your code -->
                                        <ng-template>
                                    
                                

In this example, the ngIf directive checks whether the isUserLoggedIn variable is true. If it is true, the div element with the welcome message is rendered. Otherwise, the else clause is used to render the ng-template with a message asking the user to log in.

Note : The else clause is defined using an ng-template element with a template reference variable ("#guest")

Angular ngif else example with function
                                    
                                        <div *ngIf="loginCheck(); else guest">
                                            <!-- Your code -->
                                        </div>

                                        <ng-template #guest>
                                            <!-- Your code -->
                                        <ng-template>
                                    
                                
                                    
                                        name: string = 'Sunny';
                                        loginCheck() {
                                            if(this.name === 'Sunny') {
                                                return true;
                                            }
                                            else {
                                                return false;
                                            }
                                        }
                                    
                                
That's all you need for ngIf else my friend!
  • Please refer Below links for details