Programming

How to truncate text in Angular2

25 September 2026 · 11 min read

How to truncate text in Angular2

In the world of web development, presenting information clearly and concisely is crucial. Angular, a popular framework for building dynamic web applications, offers various ways to manage and display text. One common challenge is handling lengthy text that can clutter the user interface. That’s where the ability to truncate text in Angular2 (and later versions) becomes essential. Whether you’re displaying product descriptions, news snippets, or user comments, knowing how to effectively truncate text ensures a clean and user-friendly experience. This blog post will guide you through different methods to achieve text truncation in your Angular applications, providing practical examples and best practices to help you master this important skill. We’ll explore techniques using CSS, custom pipes, and JavaScript, so you can choose the approach that best suits your project’s needs and complexity.

Understanding Text Truncation Techniques in Angular

Text truncation involves shortening a piece of text and indicating the omission, typically with an ellipsis (…). This is vital for maintaining a consistent layout and preventing text from overflowing its container. Several techniques can be employed within Angular to achieve this, each with its own advantages and disadvantages. CSS-based truncation is simple and efficient for basic scenarios where you only need to truncate at the end of a single line. Custom pipes offer more flexibility, allowing you to truncate based on character count or word count and to add custom logic. JavaScript-based solutions provide the greatest control, but can be more complex to implement and may impact performance if not optimized properly. Understanding these options enables developers to choose the best approach for their specific needs.

Selecting the appropriate truncation method depends on factors like the complexity of the text, the desired level of control, and performance considerations. For simple single-line truncation, CSS might suffice. However, if you require more complex logic, such as truncating at the nearest word or adding custom prefixes/suffixes, a custom pipe or JavaScript function might be more suitable. Before implementing any method, it’s important to analyze the requirements of your application and choose the technique that offers the best balance between functionality, performance, and maintainability. Consider using tools like Lighthouse in Chrome DevTools to measure the performance impact of different approaches.

For instance, consider a scenario where you’re displaying a list of blog post titles. If the titles are lengthy, they can disrupt the layout. Using CSS truncation, you can easily limit the title to a single line and add an ellipsis if it exceeds the container width. However, if you want to truncate the title after a specific number of words and display a “Read More” link, a custom pipe would be a better option. Furthermore, if you need to adjust the truncation dynamically based on screen size or other factors, a JavaScript-based solution might be necessary. The key is to choose the right tool for the job. According to a study by Nielsen Norman Group, users prefer concise and scannable content, so effective text truncation contributes to better user experience. Nielsen Norman Group - Web Writing for Usability highlights the importance of scannable content.

Using CSS for Simple Text Truncation

CSS provides a straightforward way to truncate text in Angular2 and later versions, particularly for single-line scenarios. This method leverages the text-overflow: ellipsis property, combined with overflow: hidden and white-space: nowrap. These properties work together to hide any overflowing text and display an ellipsis at the point where the text is truncated. This approach is simple to implement and has minimal performance overhead, making it ideal for basic truncation needs. However, it’s limited to single-line truncation and doesn’t offer much flexibility in terms of customization.

To implement CSS-based truncation, you’ll need to apply the following CSS rules to the element containing the text: overflow: hidden;, text-overflow: ellipsis;, and white-space: nowrap;. The overflow: hidden; property ensures that any text exceeding the element’s boundaries is hidden. The text-overflow: ellipsis; property adds the ellipsis (…) to indicate truncation. The white-space: nowrap; property prevents the text from wrapping to the next line, forcing it to stay on a single line. This combination of properties provides a simple and effective way to truncate text in a single line. For example, if you have a div element with the class truncate, you would add these styles to the truncate class in your CSS file.

Here’s an example of how to apply CSS-based truncation in an Angular component template:

html

This is a long line of text that will be truncated if it exceeds the container width.
css .truncate { width: 200px; / Set a fixed width for the container / overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } This approach is best suited for situations where you need a quick and easy way to truncate text without complex logic. It’s commonly used in scenarios like displaying product names in a shopping cart, showing file names in a file explorer, or presenting short descriptions in a list view. However, keep in mind that CSS-based truncation is limited to single-line scenarios and doesn’t allow for customization beyond the ellipsis. For more complex truncation requirements, you’ll need to explore other techniques like custom pipes or JavaScript functions. According to MDN Web Docs, these CSS properties are widely supported across modern browsers. MDN Web Docs - text-overflow provides further details on CSS text-overflow.

Creating Custom Pipes for Advanced Truncation

For more complex text truncation scenarios, custom pipes in Angular offer a powerful and flexible solution. Custom pipes allow you to define your own logic for truncating text based on specific criteria, such as character count, word count, or even custom delimiters. This approach provides greater control over the truncation process and allows you to tailor the truncation behavior to the specific needs of your application. You can also add custom prefixes or suffixes, such as “Read More” links, to the truncated text. This makes custom pipes a versatile tool for managing text display in Angular applications.

To create a custom pipe for text truncation, you’ll need to define a class that implements the PipeTransform interface. This interface requires you to implement the transform method, which takes the input text and any optional parameters as arguments and returns the truncated text. Within the transform method, you can implement your custom truncation logic. For example, you can truncate the text after a specified number of characters, or you can truncate it at the nearest word boundary. You can also add an ellipsis or other custom indicators to the truncated text. The following steps outline the process:

  1. Create a new pipe using the Angular CLI: ng generate pipe truncate.
  2. Implement the transform method in the generated pipe class.
  3. Add your custom truncation logic within the transform method.
  4. Use the pipe in your component template to truncate the text.

Here’s an example of a custom pipe that truncates text based on character count:

typescript import { Pipe, PipeTransform } from ‘@angular/core’; @Pipe({ name: ’truncate’ }) export class TruncatePipe implements PipeTransform { transform(value: string, limit: number = 25, completeWords: boolean = false, ellipsis: string = ‘…’): string { if (!value) return ‘’; if (value.length <= limit) return value; if (completeWords) { limit = value.substr(0, limit).lastIndexOf(’ ‘); } return value.substr(0, limit) + ellipsis; } } In your component template, you can use the pipe like this:

html {{ longText | truncate:50:’true’:’…’ }}

This example demonstrates how to truncate text to a maximum of 50 characters, ensuring that the truncation occurs at a word boundary and that an ellipsis is added to the truncated text. Custom pipes offer a powerful way to encapsulate complex text manipulation logic and reuse it throughout your Angular application. By using custom pipes, you can maintain a clean and organized codebase while providing a consistent user experience. Angular’s documentation provides comprehensive details on creating and using custom pipes. Angular Documentation - Pipes offers extensive information about Angular pipes.

JavaScript-Based Truncation for Dynamic Scenarios

While CSS and custom pipes offer effective solutions for many text truncation needs, JavaScript provides the greatest flexibility and control, especially for dynamic scenarios. JavaScript-based truncation allows you to adjust the truncation behavior based on various factors, such as screen size, device type, or user preferences. This approach is particularly useful when you need to dynamically adapt the text display to different contexts. You can implement JavaScript-based truncation directly within your Angular components or services, providing a powerful way to manage text display in complex applications.

Implementing JavaScript-based truncation involves creating a function that takes the input text and any relevant parameters as arguments and returns the truncated text. This function can then be called from your Angular component to dynamically truncate the text based on the current context. For example, you can adjust the truncation limit based on the screen width, ensuring that the text always fits within the available space. You can also use JavaScript to detect word boundaries and truncate the text at the nearest word, providing a more natural and readable truncation experience. Here are some key benefits of using JavaScript for text truncation:

  • Dynamic adjustment based on various factors.
  • Precise control over the truncation behavior.
  • Ability to implement complex truncation logic.

Here’s an example of a JavaScript function that truncates text based on character count and adds an ellipsis:

typescript truncateText(text: string, limit: number): string { if (!text) return ‘’; if (text.length <= limit) return text; return text.substring(0, limit) + ‘…’; } In your Angular component, you can use this function like this:

typescript import { Component } from ‘@angular/core’; @Component({ selector: ‘app-my-component’, template: {{ truncatedText }}

}) export class MyComponent { longText = ‘This is a long line of text that needs to be truncated dynamically.’; truncatedText: string; ngOnInit() { this.truncatedText = this.truncateText(this.longText, 50); } truncateText(text: string, limit: number): string { if (!text) return ‘’; if (text.length <= limit) return text; return text.substring(0, limit) + ‘…’; } } This example demonstrates how to use a JavaScript function to truncate text to a maximum of 50 characters and display the truncated text in an Angular component. JavaScript-based truncation offers the greatest flexibility and control, but it also requires more code and can potentially impact performance if not optimized properly. Therefore, it’s important to carefully consider the performance implications when using JavaScript for text truncation, especially in scenarios where you’re dealing with large amounts of text or complex truncation logic. Consider using memoization techniques to avoid redundant calculations. Remember to always test your implementation thoroughly to ensure that it meets the performance requirements of your application.

Infographic here
Best Practices and Considerations for Text Truncation -----------------------------------------------------

Effectively truncating text in Angular2 and later versions involves more than just implementing a truncation technique. It also requires careful consideration of user experience, performance, and maintainability. Following best practices ensures that your truncation implementation is both effective and efficient. One crucial aspect is to choose the right truncation method for the specific scenario. As discussed earlier, CSS-based truncation is suitable for simple single-line scenarios, while custom pipes and JavaScript offer more flexibility for complex requirements. Understanding the trade-offs between these different methods is essential for making informed decisions.

Another important consideration is to provide a clear indication that the text has been truncated. This is typically achieved by adding an ellipsis (…) to the truncated text. However, you can also use other visual cues, such as a “Read More” link or a tooltip that displays the full text on hover. Providing a clear indication of truncation helps users understand that the displayed text is not the complete content and encourages them to take further action if they’re interested in reading the full text. Here are some best practices to keep in mind:

  • Choose the right truncation method for the scenario.
  • Provide a clear indication of truncation.
  • Optimize for performance.
  • Ensure accessibility.

Performance is also a critical factor to consider, especially when dealing with large amounts of text or complex truncation logic. Avoid performing unnecessary calculations or DOM manipulations, as these can negatively impact the performance of your application. Use techniques like memoization and caching to optimize the truncation process. Additionally, ensure that your truncation implementation is accessible to users with disabilities. Provide alternative ways to access the full text, such as a tooltip or a separate page, for users who may have difficulty reading the truncated text Question & Answer :

Is there a way that I could limit the length of the string to a number characters? for e.g: I have to limit a title length to 20 {{ data.title }}.

Is there any pipe or filter to limit the length?

Two way to truncate text into angular.

let str = 'How to truncate text in angular'; 

1. Solution

{{str | slice:0:6}} 

Output:

how to 

If you want to append any text after slice string like

{{ (str.length>6)? (str | slice:0:6)+'...':(str) }} 

Output:

how to... 

2. Solution(Create custom pipe)

if you want to create custom truncate pipe

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'truncate' }) export class TruncatePipe implements PipeTransform { transform(value: string, args: any[]): 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; } } 

In Markup

{{ str | truncate:[20] }} // or {{ str | truncate:[20, '...'] }} // or 

Don’t forget to add a module entry.

@NgModule({ declarations: [ TruncatePipe ] }) export class AppModule {}