How to convert an attribute of an object within a list to a string separated by commas in TypeScript and Angular

I am working with an array of person objects in Angular 5 and displaying them in HTML using ngFor. The Person objects also contain an array of Role objects.

persons:Array<Person>=[];

Each Role object is structured like this:

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

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

}

Within the HTML, I am using ngFor to iterate through the persons Array within a div tag. My goal is to extract and display a comma-separated string of the role labels for each person.

Here's what I'm trying to achieve:

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

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

To simplify things, you can utilize the join method when dealing with multiple roles in the markup

<div *ngFor='let individual of individuals'>
   <p> {{ individual.roles.join(',') }} </p>
</div>

Answer №2

Start by assigning role names to your different roles and then combine them together.

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

If there is a possibility of roles being undefined or null, it's important to handle that scenario as well.

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

Answer №3

This snippet of code was the perfect solution to my issue:

 <div>
    <ng-container *ngFor="let position of user.positions"> 
        {{position.title}} + ","
    </ng-container>
 </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...

Angular 8 is throwing an error stating that the property 'token' is not recognized on the 'Object' data type

As a newcomer to Angular, I have been following the MEAN Stack - Mean Auth App Tutorial in Angular 2. However, since I am using Angular 8, some of the code is deprecated due to recent updates. I have encountered an issue with the code bel ...

Get the @types definition installed from a forked repository

Background Information I recently made a workaround for a single type definition in my fork of DefinitelyTyped. This fix is located on a specific branch within my fork. It's important to note that this fix is temporary and should not be merged back ...

Error: Bitbucket pipeline does not have the necessary permissions to complete the operation

I encountered an error while building ng build on Bitbucket. My backend is Firebase. Can you help me figure out what I'm doing wrong? EPERM: operation not permitted, lchown '/opt/atlassian/pipelines/agent/build/node_modules/.cache/angular-buil ...

In an Angular component, attempt to retrieve the data type of a class property

Discover how to retrieve the type of properties from an object by following this Typescript tutorial link. However, it seems to be behaving like Javascript and returning the value of the property instead of the type: const x = { foo: 10, bar: 'hello! ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

Unable to dynamically create a LineString using openlayers and angular

I am currently using openlayers 5 and angular6 to work on a project. I am trying to extract features from a vector layer, store them in an array, and dynamically create a LineString with the extracted data. This is my current code snippet: import * as Ex ...

Displaying an Array in HTML using Angular

Just starting out with Angular and experimenting with data display from an array. The data in the array is: [Me, Three, Four] I attempted to loop through it for printing but encountered issues. Here's a snippet of how I'm currently handling it: ...

Enhance your coding experience with code completion and autocomplete in Angular/Typescript using ATOM within

Is it possible to have Codecompletion / Autocomplete in Atom similar to Webstorm? Currently I am getting familiar with TypeScript and really enjoying it, but the lack of Codecompletion support for my HTML files in Atom is quite frustrating. Having this f ...

Typescript encounters Duplicate error when method overloading is implemented

Below is the code snippet that I am working with: public async insert(data: iFlower | iFlower[]): Promise<iFlower> | Promise<iFlower[]> { await this.insert(data); } private async insert(data: iFlower): Promise<iFlower>{ .... return d ...

Error in angular2-color-picker module: Unable to retrieve the property 'substr' from an undefined source-node in source-node.js

Error in angular2-color-picker: Issue with 'substr' property, source-node.js This error occurred when I executed: npm i --save angular2-color-picker Any suggestions on how to fix this problem? ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

Issue detected in the ngx-joyride package: Error found in ./node_modules/ngx-joyride/assets/images/close.svg

During my build process, I encountered an error with ngx-joyride: ERROR in ./node_modules/ngx-joyride/assets/images/close.svg Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type." <line x1="1" y1=" ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] I am looking to transform the above array into an Object structure as shown below: let DaysObject: any = { time: { headerName: "" }, m ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...

What is the reason behind tsc (Typescript Compiler) disregarding RxJS imports?

I have successfully set up my Angular2 project using JSPM and SystemJS. I am attempting to import RxJS and a few operators in my boot.ts file, but for some reason, my import is not being transpiled into the final boot.js output. // boot.ts import {Observa ...

Steps for downloading Excel or Zip files in Angular 4

Currently, my front end is built using Angular 4 and the back end is developed with Lumen 5.4. The task at hand requires me to export certain data as both an Excel and a zip file. I am utilizing the { saveAs } import from the package 'file-saver/Fil ...