Search code examples
angularngforng-container

How can a regular (breaking) space be added between items rendered using ng-container and ngFor in Angular to allow word wrapping


When rendering html anchor tags in an ng-container using ngFor, spaces between the tags are removed. The result is that the contents overflow the parent container.

I've tried adding a space inside a span and have used   but these get removed on rendering.

<ng-container *ngFor="let tag of tags">
    <a [innerHTML]="tag"></a>
    <span>&#32;</span>
</ng-container>

The only way I've found is to add a space and another character (eg | pipe) and to style that as transparent so not visible.

<span class="wrap-hack"> |</span>

CSS

.wrap-hack {
    color: transparent;
}

Although that works, the breaking space allows word wrapping, it's a bit of a hack. Is there a "correct" way?

Result without the hack

enter image description here

Result with hack

enter image description here


Solution

  • The issue is that by default, Angular is removing the whitespace. To prevent that, add the preserveWhitespaces component decorator.

    This Stackblitz shows the hack which is not needed with preserveWhitespaces.

    Angular Reference