ngFor 和 ngIf 显示隐藏对象细节
ngFor & ngIf to show&hide object detail
我有这样的组件
@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>
代码将显示英雄名称按钮列表。当我点击任何按钮时,我想切换 show/hide 英雄详情,但它没有发生。我该如何解决这个问题?
编辑:打字错误
您的 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
。
您可以使用以下 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>
我有这样的组件
@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>
代码将显示英雄名称按钮列表。当我点击任何按钮时,我想切换 show/hide 英雄详情,但它没有发生。我该如何解决这个问题?
编辑:打字错误
您的 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
。
您可以使用以下 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>