Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular way to convert HTML-string to text string

Tags:

angular

Currently I'm using

htmlToText(html: string) {
    const tmp = document.createElement('DIV');
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
}

for the task. What's the Angular way of doing that? Or is it perfectly fine to do like that? Can directly accessing document like that lead to problems, e.g. with mobile apps?

Note: There's an AngularJS related question, but I'm looking for an Angular2+ anwer. Plus I'm not sure whether the regex from that accepted answer is the way to go?

like image 337
bersling Avatar asked Jul 30 '26 03:07

bersling


2 Answers

you should create a pipe like this:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'htmlToPlaintext'
})
export class HtmlToPlaintextPipe implements PipeTransform {
    transform(value: any): string {
        const temp = document.createElement('div');
        temp.innerHTML = value;
        return temp.textContent || temp.innerText || '';
    }
}

and use this pipe like this:

{{htmlCode | htmlToPlaintext}}
like image 165
Mojtaba Nejad Poor Esmaeili Avatar answered Jul 31 '26 16:07

Mojtaba Nejad Poor Esmaeili


Create a pipe


    import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'htmlToPlaintext'})
    export class HtmlToPlaintextPipe implements PipeTransform {
      transform(value: string): string {
        return value? value.replace(/]+>/gm, '') : '';
      }
    }

and use this pipe in your template


    {{yourAttribute | htmlToPlaintext}}

In Angular, you should not modify the dom directly from your component. It should always be possible to use the template to achieve what you want.

like image 42
Juli3n Avatar answered Jul 31 '26 17:07

Juli3n