Prem
Prem

Reputation: 124

Split the string with comma to the newline

I need to split the string with a comma to a newline. I have tried using split and join function. It is removing commas only but not printing on a new line.

string='Lorem Ipsum,Lorem Ipsum,Lorem Ipsum'

My code is printing like this in HTML:

Lorem Ipsum Lorem Ipsum Lorem Ipsum 

It's supposed to print like this:

Lorem Ipsum
Lorem Ipsum
Lorem Ipsum

Code:

{
  'date':'Nov 12',
  'name':"Agra",
  'entities': 14,
  'details':'Lorem Ipsum,Lorem Ipsum,Lorem Ipsum'
}

getdetails(x:any){
  this.detail = x.details;
  this.s = this.detail.split(',').join('\n')
}
    <div class="col-md-4 col-12 overflow-auto test">
      <div class="alert alert-dark">No description yet <span class="font-weight-bold">+Add Description</span> </div>
      <p>{{s}}</p>

    </div

stackblitz link

Upvotes: 0

Views: 3399

Answers (5)

gavgrif
gavgrif

Reputation: 15509

When you split the string - you have an array of the component parts of the string - simply iterate over these with an ngFor and use a block level element like a p element to automatically puth them on separate lines (or use a ul with the details in li's which again are block level elements and will render on new lines).

getdetails(x:any){
this.detail = x.details;
this.s = this.detail.split(','); // creates an array you can iterate over 
}

<p *ngFor="let _s of s">{{ _s }}</p>

Upvotes: 1

Luca
Luca

Reputation: 132

You try:

<p style="white-space: pre-line;">{{s}}</p>

Upvotes: 2

Chellappan வ
Chellappan வ

Reputation: 27323

Use pre tag to defines preformatted text.

<div class="col-md-4 col-12 overflow-auto test">
      <div class="alert alert-dark">No description yet <span class="font-weight-bold">+Add Description</span> </div>
      <p>{{s}}</p>
  </div>

Example

Upvotes: 1

Passionate Coder
Passionate Coder

Reputation: 7294

If you want to display new line in template you can use <br> tag for new line. And in html file use innerHtml property for binding data for p tag

Try this

.ts

this.s = this.detail.split(',').join('<br />')

.html

<p [innerHtml]="s"></p>

Upvotes: 2

D Pro
D Pro

Reputation: 1776

this.s = this.detail.split(','); and in the template <p *ngFor="let _s of s">{{_s}}</p>

Upvotes: 1

Related Questions