What is the best way to shorten text in Angular?

I am looking to display smaller text on my website. I have considered creating a custom pipe to truncate strings, but in my situation it's not applicable. Here's what I'm dealing with:

<p [innerHTML]="aboutUs"></p>
    

Due to the tags present in the text coming from the backend, using a custom pipe is not an option for me. I need to use [innerHtml] to render the content correctly. Any advice would be appreciated.

Answer №1

To create a custom function in TypeScript that truncates text, you can use the following code:

truncateChar(text: string): string {
    let charlimit = 100;
    if(!text || text.length <= charlimit )
    {
        return text;
    }

  let without_html = text.replace(/<(?:.|\n)*?>/gm, '');
  let shortened = without_html.substring(0, charlimit) + "...";
  return shortened;
}

In your HTML file, you can call this function like so:

<div [innerHTML]="truncateChar(aboutUs)"></div>

Answer №2

It's best to avoid repeatedly calling a method from an HTML template, especially if the result is static or doesn't change frequently. This can lead to unnecessary processing.

Instead, consider calling the truncateChar method (found in @Sajeetharan's answer) from ngOnInit, ngOnChange, or any other relevant function where you update the aboutUs variable. Save the result in a separate variable within that component.

Then, utilize this variable in your template rather than directly calling the method every time.

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

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Use contextual type when determining the return type of a function, rather than relying solely on

When using Typescript 2.2.2 (with the strictNullChecks option set to true), I encountered an unexpected behavior. Is this a bug or intentional? interface Fn { (value: any): number; } var example1: Fn = function(value) { if (value === -1) { ...

What could be the reason for TypeScript throwing an error despite having a condition in place?

Having an issue with TypeScript (TS2531) and its non-null type checking. Here's the scenario: if (this.formGroup.get('inseeActivityCode') !== null) { mergedCompanyActivity.inseeActivityCode = this.formGroup.get('inseeActivityCode&ap ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Is it possible to retrieve a trimmed svg image and store it on a device using react-native-svg in React Native?

I have a modified image that I want to save in my device's gallery. Can someone please guide me on how to achieve this? My project is developed using TypeScript. Modified image: https://i.stack.imgur.com/LJOY9.jpg import React from "react"; ...

Make simultaneous edits to multiple cells in IGX GRID for Angular

Is it feasible to edit multiple cells in the same column simultaneously within igx grid Angular? I would like for the changes made within each cell to be displayed at the same time. Editing many cells all at once is a valuable feature! ...

Eliminate the need for 'any' in TypeScript code by utilizing generics and partials to bind two parameters

I'm working with TypeScript and have the following code snippet: type SportJournal = { type: 'S', sport: boolean, id: string} type ArtJournal = { type: 'A', art: boolean, id: string} type Journal = SportJournal | ArtJournal; type J ...

Is it possible to import a module that was exported in Node.js using the SystemJS import method?

When working on a Node project, we typically import modules using the require keyword. Is it possible to import the same module in an Angular 2 project using import {} from '', even if the d.ts file is not available? For instance, can I incorpora ...

Tracking events in Angular 4 using angulartics2 and Adobe Analytics: A step-by-step guide

I've been working on tracking page views in my Angular 4 application, specifically with Adobe Analytics. Currently, I am utilizing angulartics2 for this purpose. First step was adding the necessary script for Adobe Staging in my index.html page: &l ...

What's the best way to test a TSX file importing SCSS using Jest?

Here is my configuration for jest: module.exports = { roots: ['<rootDir>/src'], collectCoverageFrom: [ '<rootDir>/src/**/*.{ts,tsx}' ], coverageDirectory: 'coverage', testEnvironment: 'jsdom&apo ...

What is the best way to ensure the footer remains in an automatic position relative to the component's height?

I am struggling to position the footer component correctly at the end of my router-outlet. After trying various CSS properties, I managed to make the footer stay at the bottom but it acts like a fixed footer. However, I want the footer to adjust its positi ...

Tips for incorporating child components when creating unit tests in Angular 2

While working on my component, I encountered an issue with the child component during unit testing. An error message is appearing stating that the child component is not defined. Any advice or solutions would be greatly appreciated. Thank you in advance. ...

Unlocking 'this' Within a Promise

I seem to have an issue with the 'this' reference in the typescript function provided. It is not correctly resolving to the instance of EmailValidator as expected. How can I fix this so that it points to the correct instance of EmailVaildator, al ...

Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row. dashboard.html ...

Unable to bind click eventListener to dynamic HTML in Angular 12 module

I am facing an issue with click binding on dynamic HTML. I attempted using the setTimeout function, but the click event is not binding to the button. Additionally, I tried using template reference on the button and obtaining the value with @ViewChildren, h ...

Setting up roles and permissions for the admin user in Strapi v4 during the bootstrap process

This project is built using Typescript. To streamline the development process, all data needs to be bootstrapped in advance so that new team members working on the project do not have to manually insert data into the strapi admin panel. While inserting ne ...

Encountered a problem with regular expressions in Angular 2 - a Module parse error due to an octal literal in strict mode

Greetings, I have encountered an issue with a regular expression in my environment.ts file. export const environment = { passwordPolicy: "^(?!.*(.)\1\1)(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}.*$" }; Unfortunately, whe ...

The error message "The function 'combineLatest' is not found on the Observable type"

Hey there! I'm currently working on implementing an InstantSearch function into my website using Angular 12.2. To accomplish this, I'll be working with a Firestore database with the index "book-data". In my search component, I have included the f ...

Enabling and disabling contenteditable functionality on a div element in Angular

Issue I am facing an issue while trying to bind a boolean to the contenteditable directive of a div. However, it seems that this binding is not working as expected. Error Message: The 'contenteditable' property is not recognized as a valid p ...