codealpha98
codealpha98

Reputation: 61

Preserve trailing whitespace in html template of angular component?

I want to display a comma separated list of names like test1, test2, test3. I am using something like below:

<div style="display: inline-block;" *ngFor="let object of objectList; let i = index;">
        {{object.name}}{{((i+1) === objectList.length) ? '' : ', '}}
 </div>

All the trailing whitespaces are removed and result is test1,test2,test3. I was using &nbsp but I read at some places that it was not recommended to use. How should I preserve these whitespaces?

edit: code didn't have that style tag earlier (which is in a separate .css file in the actual code but placing it inline for the sake of the question)

Upvotes: 0

Views: 785

Answers (1)

Barremian
Barremian

Reputation: 31105

I'd suggest two changes.

  1. At the moment, each element of the array is rendered in it's own <div> tag. So it'd look like following
<div>test1, </div>
<div>test2, </div>
<div>test3, </div>
<div>test4, </div>
<div>test5</div>

Whereas you might need to enclose all the elements in a single <div> container like

<div>test1, test2, test3, test4, test5</div>

For that you could iterate the array in a <ng-container> tag. It'll be commented out in the final DOM and would render additional elements.

  1. You could use the last local variable of the *ngFor directive instead of checking using the index and the array's length.

Try the following

<div>
  <ng-container *ngFor="let object of objectList; let last = last;">
    {{ object.name }}{{ last ? '' : ', ' }}
  </ng-container>
</div>

Upvotes: 2

Related Questions