Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get line break within string interpolation in Angularjs

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}}

like image 648
Skywalker Avatar asked Dec 06 '17 15:12

Skywalker


People also ask

How do I add a line break in interpolation?

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.

How do you find a line break in a string?

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 .

What is string interpolation in AngularJS?

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.

How do you go to the next line in TypeScript?

In typescript use '\n' to add new line.


2 Answers

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'...

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

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.

like image 144
Fenton Avatar answered Oct 30 '22 10:10

Fenton


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

like image 32
Palash Roy Avatar answered Oct 30 '22 10:10

Palash Roy