【问题标题】:ngFor & ngIf to show&hide object detailngFor 和 ngIf 显示隐藏对象详细信息
【发布时间】:2017-03-09 18:01:25
【问题描述】:

我有这样的组件

@Component({
  templateUrl:"home.html",
})
export class HomePage {
  current:any
  heroes=[{name:"hero1",detail:"h1detail"}, {name:"hero2",detail:"h2detail"}]

  constructor() {

    }

    tdetail(h){
      if (current!=h.name){
          current = h.name
      }
      else{
        current = ""
      }
    }
}

和html模板home.html

<ion-navbar positive *navbar>
    <ion-title>
        Hero
    </ion-title>
</ion-navbar>
<ion-content class="xm-new-order">
  <ul class="event">
    <li *ngFor="let hero of heroes">
      <button (click)="tdetail(hero)">
        {{hero.name}}
      </button>
      <p *ngIf="current==hero.name" >
        {{hero.detail}}
      </p>
    </li>
  </ul>
</ion-content>

代码将显示英雄名称按钮列表。当我单击任何按钮时,我想切换显示/隐藏英雄详细信息,但它没有发生。我该如何解决这个问题?

编辑:错字

【问题讨论】:

    标签: angular ionic2 angular-ng-if


    【解决方案1】:

    您的tdetail(h) 函数中有错误。这里:if (current!=hero.name){,没有定义hero 变量。在这里,它被传递为h。所以,你需要像这样使用h

    tdetail(h){
      if (this.current!=h.name){
          this.current = h.name
      }
    }
    

    编辑 1: 删除 else 部分。如果您想切换,current 应该在给定点至少保留来自heros 的 1 个值。在您的 else 部分中,您正在设置 current = "";,它将当前重置为空字符串。

    编辑 2:另外,使用 this.current 而不是 current

    【讨论】:

    【解决方案2】:

    你可以使用下面的 HTML 来创建你的英雄列表:

    <ul class="event">
      <li *ngFor="let hero of heroes">
        <button (click)="hero.active = !hero.active">
          {{hero.name}}
        </button>
        <p *ngIf="hero.active">
          {{hero.detail}}
        </p>
      </li>
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多