1

I'm trying to have a new line displayed in a string in my template. For some reason the new line is ignored. <br/> is not working, neither does \n.

Here is my function:

this.errorsString = '';
this.validateData();
for ( var i = 0; i < this.errors.length; i++){
    this.errorsString += `${this.errors[i]}` +'<br/>'
    console.log(this.errors[i])
}

html:

<div *ngIf="errorsString" >
    <div class="redError">
        {{ errorsString }}
    </div>
</div>
4
  • 1
    you are using this error string with innerHTML in template? Commented Mar 22, 2021 at 8:51
  • or use \n and css style white-space Commented Mar 22, 2021 at 8:52
  • <div *ngIf="errorsString" > <div class="redError"> {{ errorsString }} </div> </div> Commented Mar 22, 2021 at 8:59
  • try this this.errorsString +=`${this.error[i]}\n` or this.errorsString += this.errors+''+'\n' Commented Mar 22, 2021 at 9:10

3 Answers 3

1

You could simply use ngFor on a "p" element. If you have a list of errors you can just iterate over them in the component template using ngFor on a Paragraph and have your line break accodingly.

app.component.ts

// An array that contains all errors which can also be filled up later, just an example
public errors = ['error1', 'error2', 'error3'];

app.component.html

<div *ngIf="errors.length != 0">
    <div class="red-error">
        <p *ngFor="let error of errors">{{ error }}</p>
    </div>
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

Try using innerHTML to write the html on the html document:

<div *ngIf="errorsString">
  <div class="redError" innerHTML="{{ errorsString }}">
  </div>
</div>

1 Comment

how about in ur ts change to this: this.errorsString += ${this.errors[i]} <br>
0

Just join the items using '<br />' and use innerHtml

  public errors = ["error1", "error2", "error3"];
  errorsString = this.errors.length > 0 ? this.errors.join("<br />") : null;

In your html

<div *ngIf="errorsString">
  <div class="redError" innerHTML="{{ errorsString }}">
  </div>
</div>

See Demo Here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.