Strip html in Angular template binding

后端 未结 2 1096
梦如初夏
梦如初夏 2021-02-06 10:51

I have a list displaying data that can sometimes contain HTML

  
  • 相关标签:
    2条回答
    • 2021-02-06 11:14

      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.

      0 讨论(0)
    • 2021-02-06 11:26

      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!

      0 讨论(0)
    提交回复
    热议问题