【问题标题】:Angular way to convert HTML-string to text string将 HTML 字符串转换为文本字符串的角度方法
【发布时间】:2018-04-29 17:40:11
【问题描述】:

目前我正在使用

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

任务。 Angular 的做法是什么?或者这样做完全没问题?可以直接访问document 这样会导致问题,例如使用移动应用程序?

注意:有一个AngularJS related question,但我正在寻找一个 Angular2+ 答案。另外,我不确定该接受答案中的正则表达式是否可行?

【问题讨论】:

    标签: angular


    【解决方案1】:

    创建管道

    从“@angular/core”导入 { Pipe, PipeTransform }; @Pipe({name: 'htmlToPlaintext'}) 导出类 HtmlToPlaintextPipe 实现 PipeTransform { 转换(值:字符串):字符串 { 返回值? value.replace(/]+>/gm, '') : ''; } }

    在你的模板中使用这个管道

    {{你的属性 | htmlToPlaintext}}

    在 Angular 中,你不应该直接从你的组件中修改 dom。应该总是可以使用模板来实现您想要的。

    【讨论】:

      【解决方案2】:

      你应该像这样创建一个管道

      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 || '';
          }
      }
      

      并像这样使用这个管道:

      {{htmlCode | htmlToPlaintext}}
      

      【讨论】:

      • 您好,您能解释一下您的答案与本页其他答案有何不同吗?
      【解决方案3】:

      要在 Angular 2+ 中将 html 呈现为字符串,我们可以使用 innerHTML 属性。例如:

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

      或者,看看这个转换器:https://www.npmjs.com/package//html-to-text

      更多信息:Angular HTML binding

      【讨论】:

        【解决方案4】:

        你需要做的是转义这些字符,然后你存档你想要的:

        " replace with &quot;
        & replace with &amp;
        < replace with &lt;
        > replace with &gt;
        

        more about escape characters

        XML / HTML / XHTML 或任何 SGML 派生词不会将这些字符解析为它们的用途。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-07-29
          • 2019-11-12
          • 2014-08-29
          • 1970-01-01
          • 1970-01-01
          • 2014-08-30
          • 2022-01-19
          相关资源
          最近更新 更多