Utilizing the Angular slice pipe within innerHTML: A comprehensive guide

I have a whatsNewDetail.content string that includes HTML elements:

<span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: justify;">In nec convallis justo. Quisque egestas mollis nibh non hendrerit. Phasellus tempus sapien in ultricies aliquet. Maecenas nec risus viverra tortor rhoncus venenatis in sit amet enim. Integer id ipsum non leo finibus sagittis in eu velit. Curabitur sed dolor dui. Mauris aliquam magna a ipsum tincidunt tempor vitae sit amet ante. Maecenas pellentesque augue vitae quam faucibus, vel convallis dolor placerat. Pellentesque semper justo a turpis euismod, ac gravida enim suscipit.</span>

When I try to use the slice pipe, it doesn't show anything. I suspect that the HTML elements are affecting the slicing process.

 <span style="font-size: 13px" [innerHTML]="whatsNewDetail.content | slice:0:15+'...'></span>

What I am aiming for is to slice the text like this:

In nec convalli...

and not like this:

<span style="fo...

Is there a way to apply the slice pipe after the text has been rendered?

Answer №1

Here is the solution I came up with. I utilized a hidden element to store the innerHTML content and introduced a template reference variable called #whatsNew.

<p hidden [innerHTML]="whatsNewDetail.content" #whatsNew></p>

Next, I defined a function that retrieves the innerText of an element.

getInnerText(el) {
  return el.innerText;
}

Then, I displayed the element using the slice pipe to limit the characters.

<p class="article-content">{{ getInnerText(whatsNew).length > 150 ? (getInnerText(whatsNew) | slice:0:150) +'...' : getInnerText(whatsNew) }}</p>

Answer №2

Here's a helpful suggestion:

To implement this technique in an HTML file, you can use the following code snippet:

<span style="font-size: 13px">
 <span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: justify;">{{whatsNewDetail.content.substring(0,15)}}...</span>
</span>

In the TypeScript file, define whatsNewDetail as follows:

whatsNewDetail= {content: `In nec convallis justo. Quisque egestas mollis nibh non hendrerit. Phasellus tempus sapien in ultricies aliquet. Maecenas nec risus viverra tortor rhoncus venenatis in sit amet enim. Integer id ipsum non leo finibus sagittis in eu velit. Curabitur sed dolor dui. Mauris aliquam magna a ipsum tincidunt tempor vitae sit amet ante. Maecenas pellentesque augue vitae quam faucibus, vel convallis dolor placerat. Pellentesque semper justo a turpis euismod, ac gravida enim suscipit.`}

This solution should effectively address your issue.

Note: If you need to expand the text by clicking on the ellipsis (...), utilize a separate span for the ellipsis and control its visibility using Angular's *ngIf directive based on the content stored in whatsNewDetail.content.

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

Add the item to the array and then use the *ngFor directive to iterate

Whenever the addRoom button is clicked, I want to add an object to an array. The problem is that the data in my array keeps getting repeated. Please excuse any language errors in my explanation. Feel free to ask me for clarification in the comments below. ...

Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0". The issue I'm facing ...

Having trouble getting the Angular Route to work, any tips on how to fix it?

I am currently learning Angular and have encountered a small issue. When I place the Component in my app.component.html as shown below, it functions correctly: <body> <div class="container"> <app-search-books></app-search-books ...

Generate a vector tile in Azure Maps containing a massive one million data points

Is it possible to use Azure maps to display a large amount of data points, such as one million? I am interested in creating an Azure map with optimized performance and loading it into my Angular application using a map URL. Can you provide guidance on how ...

Using Azure AD for authentication: Implementing Msal authentication in a React Next.js application with TypeScript and App Router

Working on a React Next.js web application with Microsoft Authentication Library (MSAL) login integration, using Azure. The app utilizes Next.js with the App Router for routing. But encountering an error when attempting to run the app: createContext only w ...

Updating the value of a form in Angular 2 for a data model with multi-select functionality

I am utilizing a multi-select library for my Angular project. This package enables me to bind to my reactive form model, which is functioning properly. Upon initializing my component, I capture the initial value from my model in a variable. Users can acti ...

Is it possible to access your app directly from the browser without requiring any user prompts?

After successfully setting up my app for both android and ios with the necessary app link and universal link, I am now focusing on redirecting users from a specific website to my app. The mobile aspect is all set, but I need to work on the browser/server s ...

XPath query for the initial descendant element of a different Angular module

When working in Angular, I'm faced with the challenge of selecting the first child component of a parent component using specific CSS (SASS) rules. The structure I have is a list of items within one component, where each item is also a component itsel ...

Oops! The react-social-media-embed encountered a TypeError because it tried to extend a value that is either undefined, not a

I recently attempted to incorporate the "react-social-media-embed" package into my Next.js project using TypeScript. Here's what I did: npm i react-social-media-embed Here is a snippet from my page.tsx: import { InstagramEmbed } from 'react-soc ...

Experiencing difficulty in retrieving data streams in Angular 5 when using the pptxGenjs library

I am working on incorporating images into a PowerPoint file using pptxGenjs in Angular5. While I have successfully retrieved the file with content, my goal is to extract the data from the PowerPoint file in base64 or a similar output format. However, all ...

Using Node with Express and TypeScript to serialize date types as epoch milliseconds universally

I am looking to update my node-based API backend to serialize all Date types as Epoch milliseconds instead of ISO format. For instance, if I have the following interface: export interface Profile { updatedAt: Date; updatedBy: string; } And when I ...

Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's. I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4). Let's delve into some code snipp ...

Tips for customizing Primeng's SplitButton to resemble a Bootstrap button styling

Hey there! I'm working on a project with a Primeng splitbutton and a Bootstrap button. You can check it out in the stackblitz link below: https://stackblitz.com/edit/angular6-primeng-hlxeod?file=src/app/app.component.html I'm having trouble cus ...

Dynamic Angular components and their content projection

Can content projection be utilized in Angular 2 components that are dynamically loaded and created at runtime, rather than being known at compilation time? ...

Is there a way to export all data from ag grid in Angular, even with a filter applied?

Recently, I integrated ag-grid into a project and encountered an issue with exporting data from the ag-grid table. The problem arose when applying a filter and exporting the CSV file, as it only contained the filtered data. My desired outcome is to export ...

Having trouble retrieving the SSM Parameter during deployment using CDK

Currently, I am facing a strange issue as I attempt to retrieve a parameter for my pipeline using the CDK SSM Parameter library: CfnParameter at 'nonProdAccountId.Parameter' should be created in the scope of a Stack, but no Stack found Despite t ...

The system does not acknowledge 'NODE_OPTIONS' as a command that can be used internally or externally, or as an operational program or batch file

While trying to build my react + vite project, I encountered an error after running npm run build. https://i.stack.imgur.com/XfeBe.png Here is a snapshot of my package.json file. https://i.stack.imgur.com/MbbmY.png ...

Struggling to make Cypress react unit testing run smoothly in a ReactBoilerplate repository

I have been struggling for the past 5 hours, trying to figure out how to make everything work. I even recreated a project's structure and dependencies and turned it into a public repository in hopes of receiving some assistance. It seems like there mi ...

Angular2 encounters an error when processing a custom HTTP request

I offer two unique services Custom HTTP client service fetch(url):any{ this.storage.fetchData('auth-token').then((token) => { let headers = new Headers(); this.prepareHeaders(headers); return this.http.fetch(url+"?token="+toke ...

How do I correctly specify the parameter type of a function when passing a React functional component as an argument in TypeScript?

I am facing an issue with type declaration for function parameters. See the code snippet below, const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => { return } Now, I need to pass the FunctionalComponent as a parame ...