Search code examples
angularif-statementangular-router

Angular - if statement to checking current route


I have modal component . l want to check if user he is come form '/tabs/tab1' or '/tabs/tab2' to display data specific data depending on current url coming form . The problem is the data are displaying both of them in modal component html , they are not listen to if statement below .

code :

    page1:boolean= false
   page2:boolean= false

  constructor(private router:Router) { 


     if (this.router.url === '/tabs/tab1') {
            this.page1= true
            this.page2= false
            this.getData()

        } else if (this.router.url === '/tabs/tab2'){
          this.page1= false 
          this.page2= true

          this.getData()

        }
}

html

  <ng-container *ngIf="page1; else page1">
   // check if page 1 route /tabs/tab1' display data page1 and hide data 
      page 2
  // for page 1 different data   
  </ng-container>
  <ng-template #page1>

  </ng-template>

  <ng-container *ngIf="page2; else page2">
   // check if page2 route /tabs/tab2' display data page 2 and hide 
       data page 1

    // Also of paga 2 different data 
  </ng-container>
  <ng-template #page2>

  </ng-template>

Solution

  • Your conditions are not working as you want

    Try this below condition

    <ng-container *ngIf="page1 && !page2">
      // Your data to show here    
     </ng-container>
    
    
    <ng-container *ngIf="page2 && !page1">
      // Your data to show here 
    </ng-container>
    

    This way if the page1 is false and page2 is true then only it will display the page2 and if page1 is true and page2 is galse then it will display that container page1

    If your want to show page1 and page2 both some time then you can manually set it true and false and only set if true page1 then display it and if true page2 then display it like this below

    <ng-container *ngIf="page1">
      // Your data to show here    
     </ng-container>
    
    
    <ng-container *ngIf="page2">
      // Your data to show here 
    </ng-container>