2

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.

Smicman
  • 92
  • 11

2 Answers2

5

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.

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
3

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.

Simon Groenewolt
  • 10,607
  • 1
  • 36
  • 64
  • Adding that inside the component (pre and/or code) didn't work. And I'd prefer to not have to set that css setting at every place where I use this component. – Smicman Sep 27 '18 at 10:19
  • 1
    You should be able to add the css to your component, so you don't have to add it all over the place. Having said that - check Lazar Ljubenović's answer, as that indicates that maybe Angular _is_ stripping your whitespace. – Simon Groenewolt Sep 27 '18 at 11:31