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

TypeScript introduces a new `prop` method that handles missing keys in objects

Is there a way to create a prop function that can return a default type if the specified key is not found in object o? type Prop = <K, O extends {}>(k: K, o: O) => K extends keyof O ? O[K] : 'Nah'; /* Argument of type 'K ...

Can we potentially extract shared components of a template?

As an example, I have numerous components designed for paged collections. Here is a template showcasing this: <div *ngIf="!isFormVisible"> <button class="btn" [ngClass]="{'btn-info': filtered, 'btn-default': !filtered}" (c ...

Exploring a nested object that is null in Angular by utilizing ngFor

I am working on a situation where ngFor is being used to iterate through an array of objects that contain another object. <div *ngFor="item of items" > <div>{{item.item1}}</div> <input name="test" [(ngModel)]="{{item.item2.ite ...

I encountered a difficulty trying to assign a value to @Input decorators in the spec file

While writing a test case for form submission, I encountered an issue where the Input decorator (e.g. station) value is reassigned during form submission. However, when attempting to define this Input value in the spec file, the component.station value is ...

Guide on exporting member formModule in angular

After compiling my code in cmd, an error message is displayed: ERROR in src/app/app.module.ts(3,10): error TS2305: Module '"C:/Users/Amir_JKO/my-first-app/node_modules/@angular/forms/forms"' does not have an exported member 'formModul ...

Tips for preventing the impact of angular mat-panel position changes on matdialog

In my Angular project, I utilized Matmenu and MatDialogModule. I needed to change the position of mat-menu, so I achieved this by adding the following snippet to my .scss file. ::ng-deep .cdk-overlay-pane { transform: translate(78%, 10%); } However, ...

Ngrx: When using CatchError, it does not trigger a dispatch of an action

Dealing with catchError in the latest version of ngrx. effect$ = createEffect(() => this.actions$.pipe( ofType(contactAction), switchMap(({ data }) => this.postService.contact(data).pipe( map(() =& ...

What steps should I follow to set up a TypeScript project that incorporates JavaScript modules compiled from PureScript?

TL;DR I am looking to develop TypeScript typings for compiled PureScript modules and include them in my npm package. I am willing to manually maintain these typings, but I am struggling with the configuration needed in tsconfig.json (up and downstream) and ...

Compare two lists in Angular 4 and verify all the elements that are common in both

Two lists are in my possession roles{admin, guest, configuration manager}(contains all roles of the system) loggedInUserRoles {admin , guest}(holds the roles of the currently logged in user) Within a user edit form, there is a checkbox for each user. M ...

Error in MEAN Stack: Unable to access the property 'companyTitle' because it is undefined

I have established a MongoDB collection named joblist in my database. Additionally, I have developed a DB schema known as jobList.js. var mongoose = require('mongoose'); const joblistSchema = mongoose.Schema({ companyTitle: String, jobT ...

Angular 6 - Use *ngIf to apply the readonly attribute to an input when a certain condition is met

In my current project, I am attempting to set a condition on an input field where if a variable equals 'view', then the readonly attribute should be added to the input. Here is the code snippet I am currently using: <input *ngIf="mode == &ap ...

Creating a customized Angular Material 2 component that utilizes the NG Value Accessor feature

Trying to create a custom component in Angular 4.4 + material beta12, but having trouble identifying the issue in my implementation. Here is the custom input I am attempting to achieve: Goal: Set a value to formControl once data is received from the se ...

"Unleash the Power of Go HTTP Server for React, Angular, and

Recently, I developed a small HTTP Server in GO specifically for static files: func wrapHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { h.ServeHTTP(srw, r) log.Printf("GET %s", r.RequestU ...

Resolve ESLint errors in _document.tsx file of next.js caused by Document<any> and ctx.renderPage = () with TypeScript usage

maxbause took the initiative to create a comprehensive boilerplate project for Next.js, complete with GraphQL and styled components in TypeScript. Check out the project here However, upon integrating ESLint into the project, I encountered several warning ...

Tips for successfully passing a prop to a custom root component in material-ui@next with TypeScript

Is there a way to properly render a ListItem component with react-router Link as the root component? Here's the code snippet in question: <ListItem to="/profile" component={Link} > Profile ...

Typescript types for the Google Calendar API

Is there anyone out there who can confirm whether the google Calendar API (via the npm package googleapis) for node.js or browser supports types that can be utilized in TypeScript? This would allow for a more strongly typed approach in projects using node ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Angular 6 compatibility issue with Bootstrap tooltips rendering title attribute

When setting up a bootstrap tooltip in an Angular template, I encountered the following issue: <img src="/img" *ngIf="tooltip.isTrue" [title]="{{toolTip.content}}" class="mb-3 ml-1" [attr.data-trigger]="'hover'" [attr.data ...

Enforcing type safety for mysql2 results in Typescript leads to robust data handling

I have been working on a project using NextJS and Typescript where I need to properly type my MySQL responses. This is the API endpoint I am working with: import { hash } from "bcrypt"; import type { NextApiRequest, NextApiResponse } from "n ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...