Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip html in Angular template binding

I have a list displaying data that can sometimes contain HTML

  <li *ngFor="let result of results">
    <span [innerHTML]="result.question.title">
    </span>
  </li>

The problem with using innerHTML is that the HTML gets parsed and rendered, so things like <p> tags will add margins and ruin the list's alignment.

I would like to strip all html tags and just output plain text.

An approach like this:

  <li *ngFor="let result of results">
    <span>
        {{result.question.title}}
    </span>
  </li>

does not strip the HTML, it just outputs the HTML as plain text.

How can I strip the HTML and leave plain text the 'Angular' way?

like image 937
Gerard Simpson Avatar asked Sep 18 '17 04:09

Gerard Simpson


People also ask

How do I display HTML inside an Angular binding?

If the HTML value contains a <script> tag, Angular by default will not render it as HTML. If you attempt to render a <script> tag through interpolation ({{ & }}), Angular will render the value as text.

How do I strip a tag in HTML?

In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM.

How can we hide or remove tags in Angular?

The ngHide directive shows or hides the given HTML element based on the expression provided to the ngHide attribute. The element is shown or hidden by removing or adding the . ng-hide CSS class onto the element.


2 Answers

I wouldn't recommend using a regex to parse html as suggested by kite.js.org. Use the browsers textContent / innerText function instead:

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

This should be much more reliable. You can still use a pipe if you like, just don't use regex to parse html!

like image 86
bersling Avatar answered Oct 01 '22 21:10

bersling


I guess there is no direct way to strip HTML tags from string, you can use Pipe, write a "Pipe" like this:

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

@Pipe({
    name: 'striphtml'
})

export class StripHtmlPipe implements PipeTransform {
    transform(value: string): any {
        return value.replace(/<.*?>/g, ''); // replace tags
    }
}

then add "StripHtmlPipe" to your module "declarations", after these steps you can use this pipe in your HTML:

<li *ngFor="let result of results">
    <span>
        {{result.question.title | striphtml}}
    </span>
  </li>

please note that the code above is not fully tested.

like image 28
kite.js.org Avatar answered Oct 01 '22 21:10

kite.js.org