[Fixed] Add new line in typescript (Angular)

Issue

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>

Solution

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>

Leave a Reply

(*) Required, Your email will not be published