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.
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.
Update:
The variable is being printed in the browser HTML like so {{title}}
You can simply add styling property white-space: pre-wrap to the div surrounding your string, where it breaks the line at new line character in the string and renders the white spaces as it is.
To check whether a JavaScript string contains a line break, we can use the JavaScript regex's exec method. We call /\r|\n/. exec with text to return the matches of newline characters in text .
String Interpolation in Angular 8 is a one-way data-binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
In typescript use '\n' to add new line.
Here are two demonstrably working versions...
Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with '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>
Solution two... you want to use HTML...
document.getElementById('example').innerHTML = 'My<br />title';
<h1 id="example">
</h1>
Use ng-bind-html if you want to allow HTML during binding.
In html add style:
<div style="white-space: pre-line">{{DialogText}} </div>
Use '\n' to add newline in the typescript.
this.DialogText = "Hello" + '\n' + "World";
Same in stackblitz: https://stackblitz.com/edit/angular-rpoxr5linebreak
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With