0

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)

1
  • 1
    What happens if you use ng-container instead of div? The problem might be that for each item of the array, a div element is created, and therefore the white space is lost. Commented May 25, 2021 at 9:00

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

yes you are right about those extra divs created but the trailing whitepaces getting removed, so there is no space after the commas. Is it because of style='dispaly: inline-block? I will try your solution with ng-container

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.