Mahadev Bhairava
Mahadev Bhairava

Reputation: 89

How to use ngFor in td tag?

I am looping in td using ngFor but for every data it creates new cell. How to display all data in one column seperated by comma.

Here is my html file :-

<div>
    <table border="1">
        <tr>
            <th>Actions</th>
            <th>FirstName</th>
            <th>LastName</th>
            <th>Age</th>
            <th>Salary</th>
            <th>Gender</th>
            <th>Email</th>
            <th>Department</th>
            <th>State</th>
            <th>City</th>
            <th>SkillSet</th>
            <th>Address</th>
        </tr>
        <tr *ngFor = "let employee of employees">
            <td>Edit | Delete</td>
            <td>{{employee.firstName}}</td>
            <td>{{employee.lastName}}</td>
            <td>{{employee.age}}</td>
            <td>{{employee.salary}}</td>
            <td>{{employee.gender}}</td>
            <td>{{employee.email}}</td>
            <td>{{employee.department}}</td>
            <td>{{employee.state}}</td>
            <td>{{employee.city}}</td>
            <ng-container *ngFor="let skill of employee.skills" >
                <td> {{skill.skillName}} </td>
            </ng-container>
            <td>{{employee.address}}</td>
        </tr>
    </table>
</div>

I am getting output like this :-

SkillSet | Address |          |
---------|---------|----------|------
JAVA     | SQL     | Varanasi |
JAVA     | SQL     | J2EE     | BTM
JAVA     | Ranchi  |          |

I want output like this :-

SkillSet         | Address |
-----------------|---------|
JAVA, SQL        | Varanasi|
JAVA, SQL, J2EE  | BTM     |
JAVA             | Ranchi  |

Upvotes: 0

Views: 1379

Answers (1)

mbojko
mbojko

Reputation: 14669

            <ng-container *ngFor="let skill of employee.skills" >

This will have one <ng-container> (and as a consequence, one td) per skill. Instead, you can simply

<td>{{ employee.skills.join(', ') }}</td>

(Which would work if skills was an array of strings. As it isn't...)

There's a few ways to join them into an array. I'm against putting too much JavaScript into the markup, but you can declare a helper function in the TS:

getSkillNames = (skills: any): string => skills.map(({ skillName}) => skillName).join(', ');

and in the template just have

<td>{{ getSkillNames(employee.skills) }}</td>

Notice, however, that the function will get reevaluated for every row, during every change detection, which can be a performance concern. I personally would run it once on loading data, like this:

this.employeesWithSkillNames = this.employees.map(({skills, ...rest}) => (
    { skillNames: getSkillNames(skills), skills, ...rest })
);

Upvotes: 2

Related Questions