【问题标题】:Rendering newline character as a string in Angular在Angular中将换行符呈现为字符串
【发布时间】:2021-09-04 00:49:08
【问题描述】:

我对此进行了很多研究,我所看到的只是有关如何将换行符显示为新行的解决方案。

我想在 Angular 视图中将 "\n" 显示为字符串。 Angular 似乎默认忽略它。

示例文本:

this.myText = "This is my \n example \n string: \n"

<div>{{ myText }}</div> 的示例输出:

"This is my example string:"

期望的输出:

"This is my \n example \n string: \n"

Stackblitz:HERE

--

style="white-space: pre-line"<pre></pre>[innerText]="myText" 不是我想做的,因为我不想将 \n 呈现为新行。

感谢您的帮助!

【问题讨论】:

    标签: javascript html css angular


    【解决方案1】:

    你只需要做到{{ myText.split('\n').join('\\n') }}

    https://stackblitz.com/edit/angular-ivy-ujcazi?file=src/app/app.component.html

    【讨论】:

      【解决方案2】:

      另一种看起来更像是“Angular 方式”的替代解决方案是为其创建一个管道:

      .ts:

      import { Pipe, PipeTransform } from '@angular/core';
      
      /*
       * Returns the newline character "\n" as a string
       *
       */
      @Pipe({ name: 'newlineAsString' })
      export class NewlineAsStringPipe implements PipeTransform {
        
        constructor() {}
      
        transform(text: string) {
          return text.split('\n').join('\\n');
        }
      }
      

      .html:

      <div>{{ myText | newlineAsString }}</div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-01
        • 1970-01-01
        • 2012-03-18
        • 2012-12-22
        相关资源
        最近更新 更多