Angular release 6: A guide on truncating text by words rather than characters

I'm currently enhancing a truncate pipe in Angular that is supposed to cut off text after 35 words, but instead it's trimming down to 35 characters...

Here is the HTML code:

<p *ngIf="item.description.length > 0"><span class="body-12-bold">Description: </span><span>{{ description | truncate:[35] }}</span></p>

And here is the Transform Pipe:

@Pipe({name: 'truncate'})
export class TruncatePipe implements PipeTransform {
    constructor(private item: SearchEntry, private config: ConfigService) { }
    transform(value: string, args: string[]): string {
        const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
        const trail = args.length > 1 ? args[1] : '...';
            return value.length > limit ? value.substring(0, limit) + trail : value;
    }
}

Answer №1

modifyText(content: string, maxLength: number, trail: String = '…'): string {
    let finalText = content || '';
        if (content) {
    const wordsArray = content.split(/\s+/);
    if (wordsArray.length > Math.abs(maxLength)) {
        if (maxLength < 0) {
        maxLength *= -1;
        finalText = trail + wordsArray.slice(wordsArray.length - maxLength, wordsArray.length).join(' ');
        } else {
        finalText = wordsArray.slice(0, maxLength).join(' ') + trail;
        }
    }
    }
    return finalText;
}

Answer №2

In case you require an output like the one shown in the image below, https://i.sstatic.net/egiNO.jpg And if your current output looks similar to the image below, https://i.sstatic.net/yDeNF.jpg

Kindly make use of the provided code snippet :

    <div class="tab-pane" id="pending_line_layer" role="tabpanel">
     <table class="db table">
      <thead>
       <tr>
        <th>name</th>
        <th>category</th>
        <th>data</th>
        <th>Action</th>
       </tr>
      </thead>

      <tbody>
       <tr *ngFor="let obj of pending_line">
        <td>{{obj.name}}</td>
        <td>{{obj.category}}</td>
        <td>{{obj.data | slice : 0 : 21}} ... {{obj.data | slice:obj.data.length - 21 : obj.data.length}}</td>
       </tr>
      </tbody>
     </table>
    </div>

Please be informed that my Angular Version is v7.3.9. For further information, refer to the image linked below: https://i.sstatic.net/pFAS7.jpg

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

Could routerLinkActive be used to substitute a class rather than simply appending one?

I have a navigation bar icon that links to an admin route. I want this icon to change its appearance when on that specific route. To achieve this, I can simply replace the mdi-settings-outline class with mdi-settings, displaying a filled version of the sam ...

Issue with Docker setup for managing a PNPM monorepo

As a newcomer to Docker, I am attempting to configure my fullstack API REST project. Within my PNPM workspace, I have two applications - a frontend built with Angular and a backend developed using AdonisJS. My goal is to create a Docker configuration for P ...

Tips for integrating external libraries (npm packages) in Ionic 4 applications

With the changes in Ionic 4, I am seeking a definitive guide on implementing third party libraries, such as "rss-parser". I have reviewed this article which seems to be the latest resource on the topic: https://ionicframework.com/docs/v3/developer-resour ...

Navigating with Angular 6 using routerlink in a child module with router-outlet specified in the parent component (app.component

I'm currently working with the RouterModule and encountering an issue with the routerLinks. The problem I am facing is that the routerLinks are not functioning properly (the anchor tags are not clickable). This issue arises because they are located w ...

Combining Rollup, Typescript, and converting images to base64 during the loading process

Having trouble preloading an image with Rollup. None of the solutions that should work seem to be effective, and I can't figure out why. Has anyone successfully managed to make this work? Here is my configuration in rollup.config.js: import image fr ...

Comparing tsconfig.json and tsconfig.build.json: what sets them apart?

Guides like those found at 1 and 2 often recommend having two separate files - tsconfig.json and tsconfig.build.json - at the root level of an NPM monorepo for TypeScript projects. What are the distinctions between these files? Is it possible to consolida ...

"Exploring the best way to open a new tab in Angular from a component

I am working on a simple Angular application with two components. My goal is to open one component in a new tab without moving any buttons between the components. Here is an overview of my application setup: Within my AppComponent.html file, there is a b ...

Using TypeORM to Retrieve Data from Many-to-Many Relationships with Special Attributes

Hey there, I'm diving into the world of TypeORM and could really use some guidance. I've been attempting to set up many-to-many relationships with custom properties following the instructions provided here However, I've run into a few iss ...

Learn the process of importing different types from a `.ts` file into a `.d.ts` file

In my electron project, the structure looks like this: // preload.ts import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron' import { IpcChannels } from '@shared/channelNames' contextBridge.exposeInMainWorld('api&a ...

The NestJs provider fails to inject and throws an error stating that this.iGalleryRepository.addImage is not a recognized function

I'm currently working on developing a NestJS TypeScript backend application that interacts with MySQL as its database, following the principles of clean architecture. My implementation includes JWT and Authorization features. However, I seem to be enc ...

Having trouble with the lodash find function in my Angular application

npm install lodash npm install @types/lodash ng serve import { find, upperCase } from 'lodash'; console.log(upperCase('test')); // 'TEST' console.log(find(items, ['id', id])) // TypeError: "Object(...)(...) is un ...

The Core.js file seems to be missing, but it can be found in the node modules directory. The Meteor client is functioning properly, but there seems to be

I encountered an issue while trying to import the meteor-client.js file. The problem arose when loading ecmascript-runtime-client, which prompted me with an error stating that the core-js npm package could not be found in my node_modules directory. Even af ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

Using Unique Typeface in Ionic Framework 3

I am currently utilizing Ionic3: Your device information: Cordova CLI: 6.4.0 Ionic Framework Version: 3.0.1 Ionic CLI Version: 2.1.18 Ionic App Lib Version: 2.1.9 Ionic App Scripts Version: 1.3.0 ios-deploy version: Not installed ios-sim version: Not in ...

A guide on implementing radio buttons in Angular 2 and sending the selected value via a HTTP post request

As a newcomer to Angular 2, I am struggling with the following code: Here is my HTML <form action="POST" (submit)="register()" class="aa-login-form"> <input type="radio" [(ngModel)]="gender" name="sex" value="MALE"> Male <input ...

Trying to understand the purpose of this Angular function has been quite puzzling for me

In my angular/node sample code, I identified a function that performs a specific task. However, I am puzzled as to why it is named differently from what I expected. By adding a console.log() statement in the code snippets, I was able to confirm that the f ...

Typescript enhances the functionality of the Express Request body

I need help with the following code snippet: const fff = async (req: express.Request, res: express.Response): Promise<void> => {...} How can I specify that req.body.xxx exists? I want it to be recognized when I reference req.body.xxx as a propert ...

I am struggling to set a required input in Angular2

I am new to Angular and currently working on a project that requires input validation to ensure that no field is left blank. The project consists of an HTML file along with a .ts file for functionality. Below is a snippet from the HTML: <div class="f ...

Exploring the Power of Asynchronous Operations with Await and Async in

I have a basic understanding of how to use await/async in Angular 2 with the following example: async getValueWithAsync() { const value = <number>await this.resolveAfter2Seconds(20); console.log(`async result: ${value}`); } In my Angular ...