【问题标题】:how to hide show different components in one component ionic 2如何在一个组件离子2中隐藏显示不同的组件
【发布时间】:2018-02-09 17:15:42
【问题描述】:

我有一个名为 HomeComponent 的组件。因为我需要根据条件显示多个组件。

我的功能在一个页面中调用不同的页面,进入 Home 组件。我正在使用 *ngIf 来显示隐藏 div(我当前的逻辑是否在我的大脑中运行 :-( )。这样我就遇到了一个问题。当我点击 component mars 时,我必须显示组成冥王星,所以一个。

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 。我已经在指定组件中有我的按钮。

【问题讨论】:

  • 使用ngSwitch怎么样?
  • 嗨,我发现并回答了它工作正常。那是使用 Events 。我能够查看不同的视图。我正在使用相同的 *ngIf 条件。我可以使用事件 emmit 引用 link 更改条件。但问题是我必须像使用 navCtrl.push 之前那样传递数据。目前对于我的解决方案,我正在使用本地存储

标签: javascript reactjs typescript ionic-framework angular2-routing


【解决方案1】:

我不熟悉 Ionic 框架,因此这可能需要调整(未经测试),但可能会让您了解如何使用 ngSwitch 来解决这个问题。

主页组件模板

  1. 你可以调整你的模板,在&lt;ion-home&gt;标签上添加ngSwitch,传入变量来开启。在这种情况下,我们打开currentPlanet。
  2. 然后您将在&lt;ion-content&gt; 标记上添加ngSwitchWhen,并传入一个字符串值。字符串值应该是您希望当前星球的值,以便显示该内容。所以当currentPlanet = 'mars' 时,元素&lt;ion-content *ngSwitchWhen="'mars'"&gt; 就会显示出来。
  3. 在行星组件标签上添加点击事件,调用home.component.ts 中的nextPlanet(string) 函数,传入下一个要前往的行星的字符串值。

<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>

主页组件打字稿文件

然后,您将在 home.component.ts 组件中拥有您的 nextPlanet() 函数。 home 组件将根据单个变量 currentPlanet 指定要显示的行星组件。

currentPlanet: string = 'mars';

nextPlanet(planet: string){
  this.currentPlanet = planet;
}

现在当组件被点击时,它将调用主控制器中的nextPlanet()函数,传入下一个行星的字符串值。

【讨论】:

  • 嗨,我遇到了一个问题,我使用 *ngIf 来隐藏显示组件。我面临的问题是视图,第二次视图没有更新
猜你喜欢
  • 2021-03-18
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多