You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular表格中实现单行独立的Read More/Read Less功能问题

解决Angular表格中Read More按钮仅影响当前行的问题

问题出在你使用了全局的isReadMore变量,所有表格行都绑定同一个状态,点击按钮时自然会同时切换所有行的展开/收起状态。要让按钮只作用于当前行,需要给每一行数据分配独立的状态。

步骤1:给每个Post添加独立的展开状态

在获取到posts数据后,为每个post对象添加isReadMore属性,初始设为true(默认收起):

// 假设你在获取数据的方法里处理
fetchPosts() {
  // 替换成你的实际数据获取逻辑
  this.posts = [/* 你的posts数据 */];
  this.posts[0].posts.forEach(post => {
    post.isReadMore = true; // 初始化每个post的收起状态
  });
}

步骤2:修改HTML模板,绑定当前行的状态

同时修正表格结构错误(tr内不能直接放置div,需将div嵌套在td内部):

<table class="table">
  <thead>
    <tr>
      <th scope="col">Text</th>
      <th scope="col">Date</th>
      <th scope="col">Comments</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let p of posts[0].posts">
      <td>
        <div [ngClass]="{'limitTextHeight': p.isReadMore}">
          {{p.post_text}}
        </div>
        <button type="button" (click)="showText(p)" style="margin-top:15px">
          {{ p.isReadMore ? 'Read More': 'Read Less' }}
        </button>
      </td>
      <td>{{p.post_date}}</td>
      <td>{{p.post_comments.length}} comment</td>
    </tr>
  </tbody>
</table>

步骤3:更新showText函数,切换当前行的状态

修改函数,接收当前post作为参数,仅切换该post的isReadMore状态:

showText(post: any) {
  post.isReadMore = !post.isReadMore;
}

这样点击每一行的按钮时,只会切换当前行对应的状态,不会影响其他行。

内容的提问来源于stack exchange,提问作者Fedy Belaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:45:33