Angular - 检查当前路由的 if 语句

Angular - if statement to checking current route

我有模态组件。我想检查用户他是来自 '/tabs/tab1' 还是 '/tabs/tab2' 以根据当前 url 即将到来的形式显示数据特定数据。问题是数据在模态组件 html 中显示了它们,它们没有听下面的 if 语句。

代码:

    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>

您的条件未如您所愿

试试下面的条件

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


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

这样,如果 page1 为 false,page2 为 true,则仅显示 page2,如果 page1 为 true,page2 为 galse,则显示容器 page1

如果你想在某个时候同时显示第 1 页和第 2 页,那么你可以手动将其设置为 true 和 false,并且仅设置如果第 1 页为真则显示它,如果第 2 页为真则显示如下

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


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

问题是您有两个模板变量 #page1, #page2 和两个组件变量 page1, page2 具有相同的名称 page1 和 page2。因此,当您说 *ngIf="page1; else page1"*ngIf="page2; else page2" 时,那些 ifs 正在寻找 #page1#page2 上的模板变量,它们是对象,因此是真实值,并且始终被评估为 true。您必须重命名模板变量或组件变量才能使用正确的变量。一种解决方案可能是更改您的模板,例如:

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

  </ng-template>

  <ng-container *ngIf="page2; else page2ref">
   // 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 #page2ref>

  </ng-template>