首页 > 解决方案 > 如何在角度 8 中使用 for 循环显示更多/隐藏更少切换以显示更多文本

问题描述

我有一个表,其数据来自循环。当我的内容文本超过 10 个字符时,应该自动出现“显示更多”链接并且应该减少文本长度。再次,当我单击“显示更多”时,文本应该再次扩展为所有/剩余字符,并带有“隐藏更少”链接。再次如果我再次单击“隐藏更少”返回到较早的位置。展开/折叠应该单独工作。这是下面的代码

home.component.html

<table>
<tr *ngFor="let items of statusdata"><td>{{items.groupname}} <span>Show more..</span></td></tr>
</table>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
declare var $: any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  statusdata: any;


  ngOnInit() {

      this.statusdata = [{"groupid":1,"groupname":"project1project1project1project1project1project1project1project1project1"},{"groupid":2,"groupname":"project2project1project1project1project1project1project1project1"},{"groupid":3,"groupname":"project3project1project1project1project1project1project1project1project1project1"}];

  }


}

标签: angulartypescript

解决方案


试试这样:

.html

<table>
    <tr *ngFor="let items of statusdata">
        <td>
            <span *ngIf="!items.showMore">   {{trimString(items.groupname,10)}}</span>
            <span  *ngIf="items.showMore">  {{items.groupname}} </span>
            <div *ngIf="items.groupname.length> 10" (click)="items.showMore = !items.showMore">Show
                <span>{{items.showMore ? 'less' : 'More'}}</span>
            </div>
        </td>
    </tr>
</table>

.ts

   constructor() {
    this.statusdata = this.statusdata.map(item => ({
      ...item,
      showMore:false,
    }));
  }

  trimString(text, length) {
      return text.length > length ? 
             text.substring(0, length) + '...' :
             text;
  }

工作演示


推荐阅读