在TypeScript中,换行符"\n"无法正常工作。

28
我正在创建一个 TypeScript 组件中的列表项,它将在用户界面中显示。这些列表项应该在不同行中显示。因此,我添加了换行符 \n 如下所示。但是列表项仍然显示在同一行上。以下是代码。有任何想法为什么它不起作用吗?

UI Display of ul list

Typescript 代码:

@Output() excludeDisplay: any = '';
@Output() includeDisplay: any = '';
includeValues: any = '';
excludeValues: any = '';

this.includeValues += this.merId + ',' + this.explodeStatus + '\n';
console.log("include values are "+ this.includeValues);
this.excludeValues += this.merId + ',' + this.explodeStatus + '\n';
console.log("exclude values are "+ this.excludeValues);
this.includeDisplay = this.includeValues;
this.excludeDisplay = this.excludeValues;

Html 代码:

<ul id="excludedUl" required>{{ excludeDisplay }}</ul>
<ul id="includedUl" required>{{ includeDisplay }}</ul>

CSS 代码:
#includedUl {
  float: right;
  width: 33%;
}

#excludedUl {
  float: right;
  width: 33%;
}

这里是可行的解决方案......https://stackoverflow.com/a/69753810/7320692 - Radim Šafrán
4个回答

35

需要使用固定宽度:

 <div style="width: 500px;white-space: pre-line">{{property}}</div>

在 TypeScript 中使用 '\n' 添加换行。


1
不需要指定“width”,只要使用“white-space: pre-line”即可解决我的问题。谢谢! - Mhd Alaa Alhaj

18

\n在html中不会造成换行。
您需要使用<br/>或将文本包装在块级元素中。

this.includeValues += this.merId + ',' + this.explodeStatus + '<br/>';
this.excludeValues += this.merId + ',' + this.explodeStatus + '<br/>';

或者

this.includeValues += '<div>' + this.merId + ',' + this.explodeStatus + '</div>';
this.excludeValues += '<div>' + this.merId + ',' + this.explodeStatus + '</div>';

@VladimirDespotovic,所以你决定给它点踩。不错。你可能在做一些不同的事情,因为<br/>是在HTML中实现换行的方式。 - Nitzan Tomer
谢谢回答。我会取消踩的。然而,n 对我不起作用,br 也是如此...... - Vladimir Despotovic
我的问题是在网页上,<br/>标签只是被显示出来了 :) 即 <br/> ......angular 预格式化了它。我正在寻找一种将 br 显示为 br 的方法..... - Vladimir Despotovic
@VladimirDespotovic 哦,那这对你来说不是正确的线程。\n 不能工作,所以没问题,关于 <br/>,有其他的线程可以讨论,例如:https://dev59.com/FWUp5IYBdhLWcg3w5KvV - Nitzan Tomer

6
如果信息仅在HTML中显示,您可以使用CSS属性white-space。 要仅打破'\n'字符,则应使用white-space: pre-line;,如此处所述,在MDN文档中查看。

1

如果您仍需要包含 \n 的原始文本用于其他用途,您可以随时调用 Str.replace 方法,将所有 \n 更改为 <br/>,以便模板按预期工作。您可以像这样执行:

this.includeDisplay = this.includeValues.replace(/\n/g, '<br />');

您可以参考MDN文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接