ngFor& ngIf显示和隐藏对象详细信息

时间:2017-03-09 07:00:10

标签: angular ionic2 angular-ng-if

我有这样的组件

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

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

编辑:拼写错误

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

您可以在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>
相关问题