0

I've looked into this quite a bit and all I'm seeing are solutions on how to show the newline character as a new line.

I want to show the "\n" as a string in an Angular view. It seems that Angular ignores it by default.

Example Text:

this.myText = "This is my \n example \n string: \n"

Example Output of <div>{{ myText }}</div>:

"This is my example string:"

Desired Output:

"This is my \n example \n string: \n"

Stackblitz: HERE

--

i.e. style="white-space: pre-line" or <pre></pre> or [innerText]="myText" is not what I want to do as I do not want to render the \n as a new line.

Thanks for the help!

2 Answers 2

3

You just need to make it {{ myText.split('\n').join('\\n') }}

https://stackblitz.com/edit/angular-ivy-ujcazi?file=src/app/app.component.html

Sign up to request clarification or add additional context in comments.

Comments

1

An alternative solution that seems more of an "Angular way" to do it would be to create a pipe for it:

.ts:

import { Pipe, PipeTransform } from '@angular/core';

/*
 * Returns the newline character "\n" as a string
 *
 */
@Pipe({ name: 'newlineAsString' })
export class NewlineAsStringPipe implements PipeTransform {
  
  constructor() {}

  transform(text: string) {
    return text.split('\n').join('\\n');
  }
}

.html:

<div>{{ myText | newlineAsString }}</div>

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.