单击应显示文本的其余部分



我是angular的新手,我有一个带有段落列表的p标签,p标签的数据(嵌套对象数组(将来自后端。我需要在一些字符限制后截断文本,并显示....show more。当用户单击p标记时,它应该显示并显示文本的其余部分。我已经找到了截断文本并显示...show more的方法。点击应该会显示特定的段落文本,但在我的情况下,所有其他被截断的段落文本也会显示全文,由于数据是嵌套的对象数组,这对我来说很棘手,我无法找到解决方案。我在下面提供stackblitz链接。任何帮助都将不胜感激。

堆叠链路

data = [
{
comments:[
{text:'this is comment',id:'1'},
{text:'this is comment',id:'2'}
]
},
{
comments:[
{text:'this is comment',id:'3'},
{text:'this is comment',id:'4'}
]
},
{
comments:[
{text:'this is comment',id:'5'},
{text:'this is comment',id:'6'}
]
}
]
showrest:boolean = false
<div *ngFor="let c of data">
<div *ngFor="let comment of c['comments']">
<p (click)="showrest=true">{{showrest?comment.text:(comment.text | slice:0:10)+'...Click to Read More'}}</p>
</div>
</div>

以下是您的操作方法,请参阅stackblitz上的此repro。每个注释都需要一个上下文,所以只需为其创建一个组件

ts:

import { Component, Input } from "@angular/core";
@Component({
selector: "app-comment",
templateUrl: "./comment.component.html",
styleUrls: ["./comment.component.css"]
})
export class CommentComponent {
@Input() comment;
showrest = false;
}

html:

<p (click)="showrest=!showrest">{{showrest?comment.text:(comment.text | slice:0:10)+'...Click to Read More'}}</p>

你这样称呼它:

app.html

<div *ngFor="let c of data">
<div *ngFor="let comment of c['comments']">
<app-comment [comment]="comment"></app-comment>
</div>
</div>

你的问题是,你的每个评论都绑定到了同一个变量(属于同一个组件(,所以当你点击一个段落时,它会更新你的变量,从而更新所有绑定的元素(这里是你的段落(。

另一个解决方案可能是在评论模型中添加一个属性,比如:

{text:'this is comment',id:'1', isFullyVisible: false},

通过这种方式,您可以使用此变量处理注释的显示。最佳解决方案取决于您打算如何处理您的评论。如果它只是一个显示器,没有其他东西,那么只需在模型中添加一个属性就足够了。

最新更新