How to display html tags as plain text in angular

I'm developing a blog using Angular. There I want to show HTML string retrieved from the database as plain text [for listing each blog post's preview]. The HTML rich-text was generated using ngx-quill.

I can able to render the rich text by using the code . But I need to render the same content as plain text.

How can I do this in an ngx-quill / Angular way. Please help! I prefer not to go for fetching DOMElement.text[] method using JavaScript.

Do Nhu Vy

41k47 gold badges181 silver badges254 bronze badges

asked Jun 22, 2020 at 1:43

2

i don't know about quill..

so may be there will be another good solution

i think you can solve this problem with pipe something like this

@Pipe[{ name: 'truncateHtml' }]
export class TruncateHtmlPipe implements PipeTransform{

    constructor[] { }

    transform[text: string ] {

        if [!text] {
            return text;
        }

        let without_html = text.replace[//gm, ' '];
        
        return without_html;
    }

}

if you don't wanna use in template

just return that value and use it

i hope it helps

answered Jun 22, 2020 at 5:38

1

I think you can use innerHTML like this

I used it before also with Quill

answered Jun 22, 2020 at 7:13

3

Basically, there are two methods for displaying HTML tags as plain text.

1. Using element: Plaintext element is deprecated which means this feature is no longer supported. Though some browsers might still support it, it is not recommended to use.

2. HTML entities: The second and only option available is using html entities. < ,> are reserved characters in HTML, In order to display this reserved characters  you have to replace them with html entities. You can learn more about entities here. You can either use entity name or entity number initializing them with  & and ending them with ;

Refer to below table for required html entities:

Sign

Description Entity name Entity number
< Less than[start of html element] < <
> Greater than[end of html element] > >
Double quotation " "
& Ampersand [ beginning of html entity] & &

Example 1: In the first example, we are using html entity names to display body element and paragraph element on web page.

HTML

    Plain text

    

        Paragraph element:

        Body element : < body > < /body >

    

Output:

Output

Explanation: In above code, “” is simply replaced by their respective html entities.

 is html element which defines preformatted text.

Example 2: In below example, we are trying to display html entity name for “/gi, ' ']; The problem with the above approach is that it may fail for malformed HTML or when the HTML content contains entities like dashes, ampersands and other punctuation codes.

How do I view the HTML code of a website?

To view only the source code, press Ctrl + U on your computer's keyboard. Right-click a blank part of the web page and select View source from the pop-up menu that appears.

Chủ Đề