Angular模板中如何在数组原始元素间添加空格显示
If you want to show all elements of your array in a single <td> separated by spaces without using *ngFor to create multiple cells, here are a couple of straightforward approaches:
1. Use Array's join() Method Directly in the Template
The easiest way is to leverage JavaScript's built-in join() method for arrays, which lets you concatenate all elements into a single string with your chosen separator (in this case, a space).
Update your template code like this:
<td>{{ obj.someKey?.join(' ') || '' }}</td>
- The
join(' ')takes each element inobj.someKeyand joins them with a space between each. - The
?.(safe navigation operator) prevents errors ifobj.someKeyisnullorundefined. - The
|| ''ensures that if the array is empty or null, the cell shows an empty string instead ofnull/undefined.
2. Create a Custom Pipe (For Reusability)
If you need this formatting across multiple components, a custom pipe can make your code cleaner and reusable.
First, generate the pipe (using Angular CLI):
ng generate pipe arrayJoin
Then update the pipe logic:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'arrayJoin' }) export class ArrayJoinPipe implements PipeTransform { transform(value: any[], separator: string = ' '): string { if (!value || !Array.isArray(value)) { return ''; } return value.join(separator); } }
Now use it in your template:
<td>{{ obj.someKey | arrayJoin }}</td>
You can also pass a different separator if needed later, like {{ obj.someKey | arrayJoin:', ' }} for commas and spaces.
Both methods will render all array elements in a single <td> with spaces between them, no extra table cells required.
内容的提问来源于stack exchange,提问作者pupil

