sasi
sasi

Reputation: 858

How to give multiple conditions in *ngIf statement in angular 6?

My navigation bar,

<div *ngIf = ("path == '/login'" && "path == '/home'") class="tabs-header-nav">
<a routerLink="/login" class="nav-link active">login</a>
<a routerLink="/bb" class="nav-link">home</a>
<a routerLink="/" class="nav-link">CC</a>
</div>

 <div *ngIf = ("path == '/aa'" || "path == '/bb'") class="tabs-header-nav">
<a routerLink="/aa" class="nav-link active">aa</a>
<a routerLink="/bb" class="nav-link">bb</a>
<a routerLink="/" class="nav-link">CC</a>
</div>

Likewise I have 5 to 6 navigation bar in my html. Now I need to display a particular navigation bar for particular page. Single if condition ( *ngIf = "path === '/aa'" ) seems to be working, where if I give multiple conditions it is not working. Could you please help me on this?

Upvotes: 1

Views: 4753

Answers (4)

Siddharth Agrawal
Siddharth Agrawal

Reputation: 11

[SOLUTION] : Simply use "&&" operator to add multiple conditions in *ngIf -

//TypeScript File - demo.ts

   //Declaration
   flag: any;
   temp_array = [];

   //Assignment
   this.flag = true;
   this.temp_array = [1,2];
<!--HTML File - demo.html-->
  
  <div *ngIf="flag && temp_array.length>0">
    Both *ngIf conditions passes
  </div>

Upvotes: 0

Aniket Avhad
Aniket Avhad

Reputation: 4145

I have created a Stackblitz demo here

I think you are doing mistake in *ngIf quotations

Upvotes: 1

AmirReza-Farahlagha
AmirReza-Farahlagha

Reputation: 1212

If you have data that may in every time be different, mostly you use of If. but if is not ok in every where. It is better that you use of switch-case in your code like:

public string TestSwitchCase(string value)
    {
        switch (value)
        {
            case "John":
                return null;
            case "Jack":
                return "Jack";
            default:
                break;
        }

        return null;
    }

Now in angular, there is best way to do this in HTML code. this is ngSwitch and use like:

<container-element [ngSwitch]="switch_expression">
 <some-element *ngSwitchCase="match_expression_1">...</some-element>
 <some-element *ngSwitchCase="match_expression_2">...</some-element>
 <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
 <ng-container *ngSwitchCase="match_expression_3">
    <!-- use a ng-container to group multiple root nodes -->
       <inner-element></inner-element>
       <inner-other-element></inner-other-element>
       </ng-container>
       <some-element *ngSwitchDefault>...</some-element>
</container-element>

For more information See: This

GoodLuck.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222552

You should go for ngSwitch that takes multiple values

<div [ngSwitch]="path">
  <div *ngSwitchCase="'/login'">...</div>
  <div *ngSwitchCase="'/home'">...</div>
</div>

Upvotes: 1

Related Questions