Tips on implementing the show more/hide less toggle feature in Angular 8 using a for loop for displaying additional text

I have a dynamic table containing data populated from a loop. When the text content exceeds 10 characters, an automatic 'show more' link should appear to allow users to see the full text by expanding it and reducing the length of the displayed content. Clicking 'show more' will expand the text to show all remaining characters with a 'hide less' link allowing users to collapse the text back to its shortened state. The expand/collapse feature should work independently for each item. Please refer to the code snippet below:

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"}];

  }


}

Answer №1

Here is an example of how you can do it differently:

.html

<table>
    <tr *ngFor="let items of statusdata">
        <td>
            <span *ngIf="!items.showMore">   {{trimText(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,
    }));
  }

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

View Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the depths of useDispatch and dispatch in React-Redux

I am currently analyzing the code written by a former colleague of mine. Based on my understanding, useDispatch accepts an object containing the action type and payload, which is then compared to all reducers to update the state accordingly. However, in t ...

Combining functions does not result in a callable function, even when the parameters fulfill the constraints of each individual function

I have encountered an issue while trying to compile a Typescript snippet: function foo(v: string) { return 'foo'; } function bar(v: string | number) { return 'bar'; } const notCallable: typeof foo | typeof bar = function() {} as any; ...

Having trouble accessing the Angular dropdown menu with Selenium in Python

As a newcomer to Selenium, I am attempting to automate the process of downloading a CSV file from calltools and uploading it to Salesforce. The dropdown menu interface for selecting options before exporting the CSV can be viewed here. Below is the HTML fo ...

Display of Navigation Bar in Angular is Not Proper

Currently diving into the world of Angular, I've encountered an issue with a material menu that isn't displaying correctly. The expected outcome based on my code should resemble this image: https://i.stack.imgur.com/z70Aq.png This snippet showc ...

Can you enforce function signatures on an existing library like rxjs using TypeScript?

My goal is to always include an error function when using rxjs's subscribe method. To achieve this, I am thinking of creating an interface by adding the following code snippet: Observable.prototype.sub = Observable.prototype.subscribe; By assigning ...

Invoking method while returning a promise in Angular/Typescript

My Angular component is designed to read XML files and parse the data to display it on an HTML table. I'm trying to enhance the functionality of the displayed data by making modifications as specific points in the XML file are reached. However, whenev ...

Implementing global user authentication state with Zustand in Next.js version 13.4.9

I'm grappling with incorporating zustand into my Next.js 13.4.9 app, specifically for managing global authentication state. Below is the code snippet I have in my application: zustand store: // /src/store/AuthStore.ts import { create } from 'zu ...

Ensure that the footer is always positioned at the bottom of the page according

I've been struggling to get my footer to stay at the bottom of the page based on content. I've tried several CSS techniques and strategies, but I'm still encountering one issue. footer { width: 100%; padding: 25px 0 25px; backgr ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

Angular Loading Spinner Issue: ExpressionChangedAfterItHasBeenCheckedError encounted

In my Angular application, I implemented a loading-spinner component that I placed in the app component next to the router-outlet using *ngIf="isLoading". This allows me to have the loading spinner visible from every part of the application. The 'is ...

Using Javascript or Typescript, update the view to display the user's name instead of their user ID

I own a collection of car models. Each individual car is associated with a unique userid. Furthermore, each user model contains both a userid and a corresponding username. In my view, I aim to showcase all of my car models alongside their respective usern ...

How can I specify the type of a property in Typescript?

Looking for a solution: type WithRequiredProperty<Type, Key extends keyof Type> = Omit<Type, Key> & { [Property in Key]-?: Type[Property]; }; export type MessageWithMdEnforced = WithRequiredProperty<IMessage, 'md'>; ex ...

Vue project encountering TypeScript error: Module not found

In my Vue project, I am encountering an issue while using TypeScript. Whenever I try to import a .vue file, I encounter a 'cannot find module...' error. https://i.sstatic.net/jUPGe.jpg The strange thing is that the intellisense only displays t ...

The data is not being displayed in the table

I am encountering an issue while attempting to populate the table with data received through props by looping over it. Unfortunately, the data is not rendering on the UI :( However, when I manually input data, it does show up. Below is my code: Code for P ...

What is the process for changing the text in a text box when the tab key on the keyboard is pressed in

When a user types a name in this text box, it should be converted to a specific pattern. For example, if the user types Text@1, I want to print $[Text@1] instead of Text@1$[Text@1]. I have tried using the keyboard tab button with e.keyCode===9 and [\t ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Compiling the configureStore method with the rootreducer results in compilation failure

Software Setup @angular/cli version: ^9.1.2 System Details NodeJS Version: 14.15.1 Typescript Version: 4.0.3 Angular Version: 10.1.6 @angular-redux/store version: ^11.0.0 @angular/cli version (if applicable): 10.1.5 OS: Windows 10 Expected Outcome: ...

Skipping necessary module in TypeScript

There are times when I struggle to locate updated type definition files for a new version of a node package I am working with. For instance, I am facing difficulty in finding a recent type definition file for Mongoose. As a result, I encounter errors when ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...