What's the best way to restrict characters in a paragraph?

I am working on an Angular application and I need to restrict the number of characters in a paragraph (p) to 50, after which it should break to a new line.

Here is the template I am using:

<section class="echeq-element-html-display border-box"
    [ngClass]="{isYoutubeVideo: isYoutubeVideo}"
    [innerHTML]="doHtmlDisplay(echeqElement)"
></section>

Typescript code:

@Component({
  selector: 'app-html-display',
  templateUrl: './html-display.component.html',
  styleUrls: ['./html-display.component.css']
})

doHtmlDisplay(eCheqElement: EcheqElement): SafeHtml {
  return this.returnSafeHtml(this.getHtml(eCheqElement));
}

And here is the CSS I have applied:

p {
  text-decoration: underline;
  text-overflow: ellipsis; /* will make [...] at the end */
  width: 50px; /* change to your preferences */
  white-space: nowrap; /* paragraph to one line */
  overflow: hidden; /* older browsers */
}

However, this approach is not working as expected.

What changes do I need to make to achieve the desired character limit?

Thank you

Additionally, there is a main.css file with the following style:

p {
  margin: 0 0 0.75em;
}

But I only want to limit the characters in this specific component and not affect the entire application.

In my Typescript file, I currently have the following function:

truncateText(selector, maxLength) {
    let element = document.querySelector(selector),
      truncated = element.innerText;

    if (truncated.length > maxLength) {
      truncated = truncated.substr(0, maxLength) + '...';
    }
    return truncated;
  }

And in the template, I am trying to implement it like this:


<section  class="echeq-element-html-display border-box" (input)="truncateText('p', 10)" [ngClass]="{isYoutubeVideo: isYoutubeVideo}" [innerHTML]="doHtmlDisplay(echeqElement)"></section>

However, the changes are not reflecting as expected.

Answer №1

Check your CSS to ensure it is working properly, especially the white-space property in your browser's dev tools.

Another option is to attempt this in TypeScript for a different approach.

document.querySelector('p').innerText = truncateText('p', 50);

function truncateText(selector, maxLength) {
    var element = document.querySelector(selector),
        truncated = element.innerText;

    if (truncated.length > maxLength) {
        truncated = truncated.substr(0,maxLength) + '...';
    }
    return truncated;
}

Answer №2

Here is an example of how to utilize the function:

displayHTML(text, limit = 50) {
 if (text.length > limit) {
  text = text.substring(0, limit);
 } else {
  text;
 }
 return text;
}

Then, in your HTML code:

<section class="custom-html-display border-box"
[ngClass]="{isVideo: isVideo}"
[innerHTML]="displayHTML(customElement, 100) | secureHtml"></section>

Make sure to use the secureHtml pipe

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

securely managing file access through lockfile.locksync in node.js

Currently, I am utilizing lockfile.locksync to secure a file in my node.js application. However, I am interested in understanding the inner workings of this utility in more detail. Despite multiple resources referring to it as a "very polite lock file util ...

Choose a specific <div> element by its unique ID and trigger a click event on it as soon as the page loads

There is a div element on my webpage tagged with the ID of #activateeditbutton. I am hoping to have this specific div trigger a click event upon the page's initial loading. In an attempt to achieve this functionality via jQuery, I have written the fo ...

Passing an identifier between components in Angular 6

My current situation: After logging in using the Login Component, I receive a response from the API like below: { code: 200, id: 4, msg: "success", user: "Sourav" } My goal is to pass this id to the Candidate Component, CV Details Component, and ...

The functionality of the Vue.js single file component is not performing as anticipated

Recently, I've been experimenting with Vue and Vue CLI. I came across this amazing vue-tabs-component that I would like to try out. Here is a snippet of my code from App.vue: <template> <div> <tabs> <tab name="Fir ...

Modify a field within MongoDB and seamlessly update the user interface without requiring a page refresh

I am currently working on updating a single property. I have various properties such as product name, price, quantity, supplier, and description. When sending the updated quantities along with all properties to MongoDb, I am able to update both the databas ...

AngularJS ng-repeat to create a series of radio button options

This particular snippet of code generates two sets of radio buttons. The first set consists of individual radio buttons, while the second set is dynamically created using ng-repeat. Users can select any of the radio buttons by clicking on them directly or ...

If the element is checked and equal to a specific value, take action

I am trying to hide one of the 3 radio buttons on my page. Although they all have the same class, each button has a different value. I attempted to write code to achieve this, but unfortunately, it is hiding all radio buttons instead of just one. Could s ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

jQuery failing to recognize multiple selection form elements

<select class="js-example-basic-multiple categories form-control" name="categories[]" style="width: 100%" multiple="multiple"> <option value=""></option> <option value="fresher">fresher</option> <option value=" ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

I am experiencing an issue with my React app deployed on Heroku where it successfully loads the home page but fails

My react application performs perfectly when run locally and is successfully deployed on heroku. However, upon clicking any link from the home page to another page, a blank page with 'not found' message appears. No other error messages are displa ...

When attempting to use `$('.classitem').submit(function(event){event.preventDefault})`, the function fails to execute

I have a question I'm eager to find an answer to. Here is the code snippet I'm working with: $('.comment').submit(function(event) { event.preventDefault() Every time I try to submit it, the page reloads instead of submitting th ...

Tips for showcasing a dataset within a table using Angular.js ng-repeat

I am encountering an issue where I have to present an array of data within a table using Angular.js. Below is an explanation of my code. Table: <table class="table table-bordered table-striped table-hover" id="dataTable" > <tbody> ...

Explore the Ability to Monitor Modifications to an Object's Property in Angular2/Typescript

Can we track changes to an object's field in Angular2/Typescript? For instance, if we have a class Person with fields firstName, lastName, and fullName, is it feasible to automatically modify fullName whenever either firstName or lastName is altered? ...

Having trouble with the express message! I can't seem to access the template I created

I am looking to receive a notification similar to an alert, as described in this link: https://github.com/visionmedia/express-messages By default, I receive something like this https://i.stack.imgur.com/9XlA9.png If I use a template, I do not get any out ...

Looking forward to the completion of DOM rendering in my Angular/Jasmine unit test!

I recently created an Angular pie chart component using VegaEmbed, which relies on Vega and D3 for its graphics. The chart is generated by providing a title and some (key, value) pairs. I managed to isolate this component and made modifications to main.ts ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

JavaScript: Append an ellipsis to strings longer than 50 characters

Can the ternary operator be utilized to append '...' if a string surpasses 50 characters? I attempted this approach, however it did not work as expected. {post.title.substring(0, 50) + post.title.length > 50 ? '...&ap ...

Running Javascript code after rendering a HandleBars template in Node/Express

I have a Node.js application where I am trying to load data into a jQuery datatable after the data has been fetched. Currently, I am able to populate the table with the data, but I am facing issues initializing the datatable. Here is how I render the temp ...