2
votes

I have an array of person objects that I displayed in HTML using ngFor Angular 5.

persons:Array<Person>=[];

the Person objects contains an Array of Role object described as below:

export class Role{
    id:string
    label:string;   
}

export class Person{
   // many attributes
   roles:Array<Person>;

}

In the HTML i am using ngFor to fetch the persons Array in div tag. and I want to get string separated comma of the roles's label for each person and display it in div.

I want something like that:

<div *ngFor='let person of persons'>
   <p> {{ person.roles.label.join(',') }} </p>
</div>

Thanks for help

3

3 Answers

2
votes

You can just use join on the roles in the markup

<div *ngFor='let person of persons'>
   <p> {{ person.roles.join(',') }} </p>
</div>
0
votes

You can map your roles to role names first and then join them together.

<div *ngFor='let person of persons'>
    <p> {{ person.roles.map(role => role.label).join(',') }} </p>
</div>

If roles can be undefined or null you should also guard against that case.

<div *ngFor='let person of persons'>
    <p> {{ (person.roles || []).map(role => role.label).join(',') }} </p>
</div>
0
votes

This code relves my probelm:

 <div>
    <ng-container *ngFor="let role of person.roles"> 
        {{role.label}} + ","
    </ng-container>
 </div>