所以我正在尝试做一些非常简单的事情,但我被卡住了。我有一个 String
变量并在该变量内我想设置换行符,以便文本的某些部分转到新行。
我试过的:
title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
我尝试了很多变化,但它只是不起作用。我是不是很愚蠢并且遗漏了一些非常明显的东西?
不是重复的,因为我尝试过
<br/>
它没有奏效。更新:
该变量正在浏览器 HTML 中打印,如下所示
{{title}}
最佳答案
这是两个明显有效的版本...
白色空间
解决方案一...如果您希望在 HTML 中尊重换行符...(使用反引号字符串,或使用 'My \ntitle'
...
document.getElementById('example').innerHTML = `My
title`;
h1 {
white-space: pre;
}
<h1 id="example">
</h1>
Angular 版本:
<h1 style="white-space: pre;">{{title}}</h1>
HTML 中断
解决方案二……你想使用 HTML……
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
如果你想使用 ng-bind-html allow HTML during binding .
关于javascript - 如何在Angularjs中的字符串插值中获得换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678148/