我有情态成分。我想检查用户是来自'/tabs/tab1'
还是'/tabs/tab2'
,以根据当前的URL来显示特定于数据的数据。问题在于数据正在模态组件html中显示它们两者,它们不在下面的if语句中监听。
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>
您的条件无法满足您的要求
请在以下条件下尝试
<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
如果您想同时显示page1和page2,则可以手动将其设置为true和false,并且只有在true的情况下才显示它,然后在true的情况下将其显示,如下所示。>
<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"
时,那些if会寻找#page1
和#page2
上的模板变量,这些变量是对象,因此为真实值,并且始终被评估为true。您必须重命名模板变量或组件变量才能使用正确的变量。一种解决方案可能是更改模板,例如: