Search code examples
angularng-content

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


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.


Solution

  • 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.