innerHtml 在 angular 5 中不起作用

aby*_*e85 1 angular

我正在尝试显示一个包含换行符和换行符的 json 字符串;\r\n

这是json:

 {
   "Content": "OFCH\r\nPVC Double Glazed Windows\r\nMains Services"
 }
Run Code Online (Sandbox Code Playgroud)

这是 HTML:

<p class="PropertyBrochure__DescriptionContent" [innerHTML]="description.Content"></p>
Run Code Online (Sandbox Code Playgroud)

这是输出:

OFCH PVC Double Glazed Windows Mains Services
Run Code Online (Sandbox Code Playgroud)

如您所见\r\n,json 字符串中的 被剥离并被忽略。我错过了什么吗?

Rob*_*sen 5

回车既不会被剥离也不会被忽略。HTML 将被 Angular 解析为:

<p class="PropertyBrochure__DescriptionContent">OFCH
PVC Double Glazed Windows
Mains Services</p>
Run Code Online (Sandbox Code Playgroud)

问题在于浏览器的 HTML 渲染器会折叠空白区域,并希望您使用<br>元素来强制换行。

或者,您可以使用 CSS 控制浏览器对空白的处理(请参阅此处的文档):

.PropertyBrochure__DescriptionContent { white-space: pre; }
Run Code Online (Sandbox Code Playgroud)
<p class="PropertyBrochure__DescriptionContent">OFCH
PVC Double Glazed Windows
Mains Services</p>
Run Code Online (Sandbox Code Playgroud)