首页 > 解决方案 > Angular - 使用 \n 渲染 Markdown

问题描述

我正在尝试在 Angular 应用程序中呈现 Markdown。

我在 Angular 5 中使用了 ngx-markdown,它运行良好。

但是,我不得不升级到 Angular 8,从那时起,\n就不再渲染了。我读到使用 Angular 6,空格不再保留,这可能是问题所在。

ngx-markdown通过添加指令来提出修复,ngPreserveWhitespaces但它仍然不起作用。

我尝试了另一个库ngx-md,但它也无法渲染\n

使用ngx-markdown

<markdown ngPreserveWhitespaces >
    # Title \n ## Subtitle
</markdown>

使用ngx-md

<ngx-md>
  # Title \n ## Subtitle
</ngx-md>

他们都渲染了这个:

在此处输入图像描述

我也尝试过 .split('\n') 并使用 *ngFor 渲染结果,但结果并不完美。某些文本块需要立即呈现,例如代码块。

编辑

感谢 Andrei Tătar,我几乎没有进步。

像这样渲染降价有效:

<markdown ngPreserveWhitespaces >
    # Title &#x0a; ## Subtitle
</markdown>

但不是这样:

const content = "# Title &#x0a; ## Subtitle"

<markdown ngPreserveWhitespaces [data]="content" >        
</markdown>

可悲的是,这正是我所需要的

标签: htmlangularmarkdown

解决方案


\n表示 javascript 中的新行。Html 有不同的语法。您可以使用 html 在 html 中添加此字符&#x0A;

注意:您仍然需要使用: ngPreserveWhitespaces

<markdown ngPreserveWhitespaces >
# Title  &#x0a; ## Subtitle
</markdown>

https://stackblitz.com/edit/ngx-markdown-ps7x5j?file=src/app/app.component.html


推荐阅读