0

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 <quill-view [content]="post.content"></quill-view>. 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.

Vy Do
  • 46,709
  • 59
  • 215
  • 313
Joseph Jojo John
  • 500
  • 1
  • 7
  • 19

2 Answers2

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(/<(?:.|\n)*?>/gm, ' ');
        
        return without_html;
    }

}

if you don't wanna use in template

just return that value and use it

i hope it helps

RealTak
  • 96
  • 1
  • 5
  • 1
    this solution worked for me. But after this pipe operation I there was some additional spaces and line breaks. To remove that I have added the below regex. .replace(/ +(?= )/g,'') // To replace more than one spaces .replace(/ /gi," ") // To replace HTML encoded character (here  ) .replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\n\n") // to replace multiple new lines Adding these expressions to the pipe worked perfectly for me. – Joseph Jojo John Jun 22 '20 at 10:25
1

I think you can use innerHTML like this

<div [innerHTML]="blogPost"></div>

I used it before also with Quill

  • The variable "blogPost" has an HTML string. you solution will show the contents as it is. I need to show it as a plain text. So no HTML tags will be available in the string "blogPost". – Joseph Jojo John Jun 22 '20 at 09:56
  • This will render the HTML string. But I needed to render it as only plain text. The above answer worked for me, there it will strip out all the HTML tags to that I can get plain text. – Joseph Jojo John Jun 22 '20 at 17:19
  • The variable "blogPost" as an HTML string. My requirement is to remove those HTML tags to that I can show the contents as plain text. But using the solution that you have mentioned, it will render the text as rich-text. The above answer(using pipe stripping out the HTML tags to get a plain text) is the working solution for me. – Joseph Jojo John Jul 14 '20 at 20:37