我想像手风琴一样折叠和展开我的json对象的详细信息。我已经使用过loop和* ngFor指令。
toggleCollapse(){
this.isCollapsed=!this.isCollapsed;
}
<div class='wrapper' *ngFor="let t of response.articles">
<div class='img-wrapper' *ngIf="isCollapsed">
<img src='{{t.imgUrl}}' />
</div>
<div class='text-wrapper'>
<h2>{{t.title}}</h2>
<h5>{{t.description}}</h5>
<div *ngIf="!isCollapsed ">
<h5>{{t.content}}</h5>
</div>
<button *ngIf="isCollapsed" type="button" (click)="toggleCollapse()" class="btn btn-danger">Read more</button>
<button *ngIf="!isCollapsed" (click)="toggleCollapse()" class="btn btn-danger">Read less</button>
</div>
我编写此代码。当我单击“更多”按钮时,所有已展开的对象。 我应该只需要扩展单击的对象。该怎么办? 谢谢。
答案 0 :(得分:0)
@Ruwan,这个想法(没有.ts)
<div class='wrapper' *ngFor="let t of response.articles">
<!--use t.isCollased, not only isCollapsed -->
<div class='img-wrapper' *ngIf="t.isCollapsed">
<img src='{{t.imgUrl}}' />
</div>
<div class='text-wrapper'>
<h2>{{t.title}}</h2>
<h5>{{t.description}}</h5>
<div *ngIf="!t.isCollapsed ">
<h5>{{t.content}}</h5>
</div>
<--in buttons we change directy the value of t.iscollapsed-->
<button *ngIf="isCollapsed" type="button" (click)="t.isCollapsed=false" class="btn btn-danger">Read more</button>
<button *ngIf="!isCollapsed" (click)="t.isCollapsed=true" class="btn btn-danger">Read less</button>
</div>
看到我唯一做的就是用t-isCollapsed替换iscollapsed。什么是“ t.collapsed”?好是您的对象的属性response.articles。
认为response.articles就像
[
{imgUrl:"",title:"",description:"",content:""},
{imgUrl:"",title:"",description:"",content:""},
...
]
我们添加了一个新属性“ isCollapsed”,以使响应成为文章。
[
{imgUrl:"",title:"",description:"",content:"",isCollapsed:true},
{imgUrl:"",title:"",description:"",content:"",isCollapsed:false},
...
]
我们如何添加此“额外”属性?
无需修改.ts的工作原理,因为当您有一个对象数组时,可以直接添加一个属性(如我们所述,在.html中)。但是您更喜欢在.ts中添加此属性。在这种情况下,您唯一需要的就是
//I supouse you have some like
this.httpClient.get(...).subscribe(response=>{this.response=response})
//replace the line before to transform the response using "map" and spread operator
this.httpClient.get(...).subscribe(response=>{
this.response={
...response, //all properties of response
//but articles we add a property isCollapsed
articles:response.articles.map(a=>{
...a,
isCollapsed:true
})
})