typescript 如何在 Angularjs 中的字符串插值中获得换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47678148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get line break within string interpolation in Angularjs
提问by Skywalker
So I'm trying to do something very simple and I'm stuck. I have a String
variable and within that variable I Wanna set line break so certain part of the text goes to new line.
所以我正在尝试做一些非常简单的事情,但我被卡住了。我有一个String
变量,在该变量中我想设置换行符,以便文本的某些部分转到新行。
What I have tried:
我尝试过的:
title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
I have tried many variations but its just not working. Am I being stupid and missing something very obvious?
我尝试了很多变体,但它只是不起作用。我是不是很愚蠢,遗漏了一些非常明显的东西?
Not a duplicate as I have tried the <br/>
and it has not worked.
不是重复的,因为我已经尝试过了<br/>
,但没有奏效。
Update:
更新:
The variable is being printed in the browser HTML like so {{title}}
该变量正在像这样在浏览器 HTML 中打印 {{title}}
回答by Fenton
Here are two demonstrably working versions...
这里有两个明显有效的版本......
White Space
空白
Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'
...
解决方案一...如果您希望在 HTML 中尊重换行符...(使用反引号字符串,或'My \ntitle'
...
document.getElementById('example').innerHTML = `My
title`;
h1 {
white-space: pre;
}
<h1 id="example">
</h1>
Angular Version:
角度版本:
<h1 style="white-space: pre;">{{title}}</h1>
HTML Break
HTML 中断
Solution two... you want to use HTML...
解决方案二...你想使用HTML...
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
Use ng-bind-html if you want to allow HTML during binding.
如果您想在绑定期间允许使用 HTML,请使用 ng-bind-html 。
回答by Palash Roy
In html add style:
在html中添加样式:
<div style="white-space: pre-line">{{DialogText}} </div>
Use '\n' to add newline in the typescript.
使用 '\n' 在打字稿中添加换行符。
this.DialogText = "Hello" + '\n' + "World";
Same in stackblitz: https://stackblitz.com/edit/angular-rpoxr5linebreak
在stackblitz中相同:https://stackblitz.com/edit/angular-rpoxr5linebreak
回答by Iman Norouzi
You can also use a readonly textarea
element instead of <div
or <p>
to keep the format of original string.
您还可以使用 readonlytextarea
元素代替<div
或<p>
保留原始字符串的格式。
回答by kumar chandraketu
try like this
像这样尝试
<div ng-bind-html="myMsg"></div>
$scope.myMsg = `Below is the result: <br>Successful:1, <br>Failed:2` // Use backtick
回答by Brdavs
You have done the right thing. But if you are showing this in a browser, the \n means didley.
你做对了。但是,如果您在浏览器中显示此内容,\n 表示 didley。
You have to do:
你必须做:
title: string = "My<br>Title"
Now if you are using a fancy front end tool like React, you will have to deal with unsafe HTML in strings...
现在,如果您正在使用像 React 这样的高级前端工具,您将不得不处理字符串中不安全的 HTML...