Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Conditions in ngIf in Angular 6

I want to hide one div and want to show another for that I have written below code

My Code

My problem is I have used multiple conditions in ngIf but not working properly. Once I click on "Show sub content1" want to hide main content and want to show "Sub Content 1" and vise versa for all buttons. What should I do for this. Please help.

like image 854
vedankita kumbhar Avatar asked Jan 01 '23 23:01

vedankita kumbhar


2 Answers

Your were just near to your result and looking into your code looks like you are learning, Good Work!! you have to check just if any one of the content is enable so you need to hide All of the three buttons and display your Sub contents. Below is the correct code as per your requirement,

<!-- Display all of the SubContents is disable. -->
<div *ngIf="!showSubContent && !showSubContentTwo && !showSubContentThree">
     <button (click)="showSubContent=!showSubContent">Show Sub content1</button>
     <button (click)="showSubContentTwo=!showSubContentTwo">Show Sub content2</button>
     <button (click)="showSubContentThree=!showSubContentThree">Show Sub content3</button> 
     <h2>  Main content </h2>
</div>

<!-- Display if SubContent-1 is enable. -->
<div *ngIf="showSubContent && !showSubContentTwo && !showSubContentThree">
    Sub Content 1 here
    <button (click)="showSubContent=!showSubContent">Show Main Content</button>
</div>

<!-- Display if SubContent-2 is enable. -->
<div *ngIf="showSubContentTwo && !showSubContent && !showSubContentThree">
    Sub Content 2 here
    <button (click)="showSubContentTwo=!showSubContentTwo">Show Main Content</button>
</div>

<!-- Display if SubContent-3 is enable. -->
<div *ngIf="showSubContentThree && !showSubContentTwo && !showSubContent">
    Sub Content 3 here
    <button (click)="showSubContentThree=!showSubContentThree">Show Main Content</button>
</div>
like image 188
Nasiruddin Saiyed Avatar answered Jan 04 '23 12:01

Nasiruddin Saiyed


You could simplify your code using ngSwitch:

<div [ngSwitch]="showSubContent">

  <div *ngSwitchDefault>
      <button (click)="showSubContent=1">Show Sub content1</button>
      <button (click)="showSubContent=2">Show Sub content2</button>
      <button (click)="showSubContent=3">Show Sub content3</button> 
      <h2>  Main content </h2>
  </div>

  <div *ngSwitchCase="1">
      Sub Content 1 here
  </div>

   <div *ngSwitchCase="2">
      Sub Content 2 here
  </div>


  <div *ngSwitchCase="3">
      Sub Content 3 here
  </div>

  <button *ngIf="showSubContent" (click)="showSubContent=0">Show Main Content</button>
</div>
like image 21
sloth Avatar answered Jan 04 '23 12:01

sloth