Angular ng-content is losing newlines. How can I keep newlines intact?

1.6k Views Asked by At

I have an Angular Component made for displaying code, which looks like this:

<pre><code>
<ng-content></ng-content>
</code></pre>

I use this component in the following manner:

<app-example-code>
      <![CDATA[
      test
      xyz
      ]]>
</app-example-code>

Which yields "test xyz". When using

<pre><code>
test
xyz
</code></pre>

I get the expected line break.

So apparently ng-content seems to lose the line break. Is there a way I can force ng-content to keep those line breaks?

EDIT: Doing what the commenter suggested, I got it to work with using

<app-example-code><pre>
      <![CDATA[
      test
      xyz
      ]]>
</pre></app-example-code>

I would have preferred to be able to use app-example-code without adding every time, but I guess I'm happy as long as it works.

2

There are 2 best solutions below

1
On BEST ANSWER

Two things are happening here.

HTML

By default, most elements collapse whitespace into a single space character. If this wasn't the case, writing something like

<p>
  paragraph
</p>

would have quite a bit of whitespace at the start and at the end, especially if it's found within a deeply nested structure.

To display whitespace, you can use CSS:

p { white-space: pre }

Angular

On the other hand, since version 6, Angular also strips whitespace by default. You can change this option per component by configuring its metadata:

@Component({
  preserveWhitespaces: true,
})

There's also an option to do it globally.

2
On

I don't think it is Angular that is 'losing' line-breaks. This is how HTML works. You can use white-space: pre in your css to keep the line-breaks (and spaces).

Update: check Lazar Ljubenović's answer, maybe it is Angular after all. That is only about whitespace in the template, but if this component is used in another's template that will be the case.