How to get line break within string interpolation in Angularjs

前端 未结 5 1829
萌比男神i
萌比男神i 2021-01-05 10:15

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

相关标签:
5条回答
  • 2021-01-05 10:53

    You have done the right thing. But if you are showing this in a browser, the \n means 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...

    0 讨论(0)
  • 2021-01-05 10:56

    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.

    0 讨论(0)
  • 2021-01-05 11:03

    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

    0 讨论(0)
  • 2021-01-05 11:08

    You can also use a readonly textarea element instead of <div or <p> to keep the format of original string.

    0 讨论(0)
  • 2021-01-05 11:17

    try like this

    <div ng-bind-html="myMsg"></div>
    
    $scope.myMsg =  `Below is the result:  <br>Successful:1,  <br>Failed:2`  // Use backtick
    
    0 讨论(0)
提交回复
热议问题