我有一个名为 HomeComponent 的组件。因为我需要根据条件显示多个组件。
我的功能在一个页面中调用不同的页面,进入主页组件。我正在使用 *ngIf 来显示隐藏 div(我当前的逻辑在我的大脑中运行:-( )。这样我就陷入了一个问题。当我点击 component mars 时,我必须显示组件 pluto ,所以一个。
home.component.html
<ion-home>
<ion-content *ngIf="mars==true">
<component-mars>
//consider this as the code inside the component plz
<button (click)="gotoPluto()">component mars</button>
</component-mars>
</ion-content>
<ion-content *ngIf="pluto==false">
<component-pluto>
//consider this as the code inside the component plz
<button (click)="gotoEarth()">component mars</button>
</component-pluto>
</ion-content>
</ion-home>
mars.component.ts
gotoPluto(){
mars= false; // so the mars should hide
pluto=false; //so the pluto will hide and show earth
}
我的家庭组件如何检测到这个。我尝试使用 ion-tabs navController 但它有 tab-bar 。我已经在指定的组件中添加了按钮。
最佳答案
我不熟悉 Ionic 框架,因此这可能需要调整(未经测试),但可能会让您了解如何使用 ngSwitch
来解决这个问题.
主页组件模板
- 您可以调整模板以添加
ngSwitch
关于<ion-home>
标签传递变量以打开。在本例中,我们打开currentPlanet
。 - 然后您将添加
ngSwitchWhen
关于<ion-content>
标签传入一个字符串值。字符串值应该是您希望当前行星的值,以便显示该内容。那么当currentPlanet = 'mars'
元素<ion-content *ngSwitchWhen="'mars'">
将显示。 - 在行星组件标记上添加一个点击事件,调用
nextPlanet(string)
函数位于home.component.ts
传入下一个要去的星球的字符串值。
<ion-home [ngSwitch]="currentPlanet">
<ion-content *ngSwitchWhen="'mars'">
<component-mars
(click)="nextPlanet('pluto')">
</component-mars>
</ion-content>
<ion-content *ngSwitchWhen="'pluto'>
<component-pluto
(click)="nextPlanet('earth')">
</component-pluto>
</ion-content>
</ion-home>
主页组件 typescript 文件
然后您将拥有您的 nextPlanet()
在您的 home.component.ts
中运行成分。 home 组件将根据单个变量决定显示哪个行星组件 currentPlanet
.
currentPlanet: string = 'mars';
nextPlanet(planet: string){
this.currentPlanet = planet;
}
现在,当单击该组件时,它将调用 nextPlanet()
家庭 Controller 中的函数传递下一个行星的字符串值。
关于javascript - 如何隐藏在一个组件ionic 2中显示不同的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45986693/