Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything.

//model

export interface UserModel { 
       room: Map<number,number> 
}


//service

export class UserService {
  user: UserModel;

  newUser: UserModel = {
    room: new Map<number,number>(),
....}}


//html
 <tbody>
      <tr *ngFor="let user of $users | async">
        <td>{{user.room}}</td> // user.room.first???
      </tr>
      
 </tbody>

Any suggestions would be greatly appreciated!

Answer №1

It seems like there may be some confusion about how to use *ngFor in this scenario. The *ngFor directive is typically used for iterating over arrays, not Maps. If your data type is a Map, you will need to convert it into an array in order to properly use *ngFor.

If you could provide more details about the desired end result, I may be able to offer a more tailored solution to your issue.

Based on my understanding, it appears that you are trying to display the values associated with each key in a table format.

In order to achieve this, you will need to convert the keys of the Map into an array. You can do this using the following code snippet:

this.keys = Object.keys(this.user)

Add this line to your .ts file, and then incorporate the following code into your HTML:

<tbody>
  <tr *ngFor="let key of keys | async">
    <td>{{user[key]}}</td>
  </tr>

By following these steps, you should be able to achieve your desired outcome. Let me know if you need any further assistance.

Answer №2

If you want to utilize a map in an Angular template, it is advisable to first convert it to an array or object.

getArray(map){
  return Array.from(map.keys());
}

Afterwards, you can easily access it within your Angular template.

  <tr *ngFor="let element of getArray(map)">
     <!-- element[0] is key && element[1] is value -->
    <td>{{element[0] - element[1]}}</td>
  </tr>

To improve efficiency, you can store the converted array in a variable as shown below.

public mapArray;
public map;

constructor() {
  this.map = new Map();
  this.mapArray = [];
}

public ngOnInit() {
  this.doSomeThing();
  this.convertMapToArray();
}

private doSomeThing(){
  this.map.set('my_key_1', 'my_value_1');
  this.map.set('my_key_2', 'my_value_2');
}

private convertMapToArray(){
  this.mapArray = Array.from(this.map.keys());
}

<tr *ngFor="let element of mapArray">
  <!-- element[0] is key && element[1] is value -->
  <td>{{element[0] - element[1]}}</td>
</tr>

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

What could be causing the OnInit lifecycle hook to fail to execute properly?

I'm having trouble with this code. Every time I run it, the console throws a type error saying it can't read property sort. Does anyone have any ideas on how to fix this? import { Component, OnInit, Input } from '@angular/core'; impor ...

Unable to bring in the directive from the Angular library

I've created this custom Directive within my library: @Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { constructor( readonly tpl: TemplateRef<any>, private re ...

When closing a Bootstrap modal, the modal overlay does not automatically close along with it

Need assistance with a functionality where new requests can be added and existing requests can be edited using a single component that regenerates with the correct data when needed. Below is the code for the base component: home-component.html <ul c ...

Problem with deploying Angular 2 project on Github

My process began with executing this command: npm i -g angular-cli-ghpages Then, I proceeded to run the following command: ng github-pages:deploy Despite my efforts, I consistently encounter the same message: The specified command github-pages:deploy is ...

Creating dynamic CSS in Angular 2 and beyond

When working with a JavaScript variable containing style information, I encountered different approaches in AngularJS and Angular2+: menuBgColor = "red"; In AngularJS, I could use dynamically embedded styles like this: <div> <style> ...

Error in React: Trying to access property 'functionName' of an undefined object on click event

I am facing an issue while trying to click a button in my React component that is supposed to trigger a function with a parameter named "item" which is defined within the function. The pseudo-HTML snippet for this scenario looks like: <div>{item.cre ...

The Angular component fails to refresh after removing an image

After deleting an image, I have been struggling to find a way to update my component instantly without having to refresh the page. Despite trying various methods like using ChangeDetectorRef, I haven't been successful. Any advice on how to achieve thi ...

Setting the height of a rich HTML editor component can be achieved in a few simple

Seeking guidance regarding adjusting the height of the editing area while using Quill, the rich html editor in my angular component. I am currently utilizing angular-7, bootstrap, and font-awesome, all at their latest versions. Despite thorough research, ...

Guide to showcasing a stomp client's message in the view without having to refresh the page when a new message is delivered

I'm in the process of setting up a chatroom with Angular and web-socket. I want to update the view with new messages from the socket without having to refresh the page. The message is appearing in the log console but not on the page. Any suggestions w ...

Having trouble installing npm packages due to an error

As I attempt to install my npm packages, a frustrating error occurs. What steps should I take to resolve this issue? npm ERR! code EINVALIDTYPE npm ERR! typeerror Error: Argument #5: Expected object but got string npm ERR! typeerror at inflatableChild ...

When using Angular 4 CanActivate guard in conjunction with a service, the component may not load properly. However, by simply using Observable

When attempting to implement the CanActivate guard in Angular, I encountered an issue where it didn't work when calling a service and using return true, or even return Observable.of(true);. However, the guard did work and the component loaded success ...

Ways to verify function arguments within an asynchronous function using Jest

I have a function that needs to be tested export const executeCommand = async ( command: string ): Promise<{ output: string; error: string }> => { let output = ""; let error = ""; const options: exec.ExecOptions = { ...

Display a loading indicator with the shortest possible delay whenever utilizing the React Router v6 Link functionality

Integrate React and Router v6 App.tsx: const Page1 = lazy(() => pMinDelay(import('./views/Page1'), 500)) const Page2 = lazy(() => pMinDelay(import('./views/Page2'), 500)) return ( <Suspense fallback={<Loading/>}gt ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

Unable to create the editor within Angular framework

I'm in the process of developing a code editor There's a component that is rendered conditionally <ace-editor [(text)]="text" #editor style="height:150px;"></ace-editor> Within the ngAfterViewInit Lifecycle hook ...

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

Maintaining scroll position in React Router v6

My website's homepage displays a user's feed. When a user clicks on one of the feed cards, they are taken to a different URL. However, when the user returns to the homepage, it automatically scrolls to the top. I am looking for a way to preserve ...

Guide on creating a dash-patterned line over a rectangle using PixiJS and Angular

https://i.sstatic.net/uIksi.jpg In this example, we are creating a PixiJS application that draws a solid-stroked rectangle. Unfortunately, PIXI.Graphics does not have a built-in feature to draw dashed strokes. import { Component, OnInit } from &ap ...

Angular: Extracting data from mat select by id

I'm in the process of designing a dynamic form that includes multiple dropdowns (mat-select). The challenge I am facing is that the select element only holds the key and not the actual value. This has left me unsure about how to display the selected v ...