How can we loop through an array of Map<string, string> using ngFor?

There is a property set up as follows:

const carac = new Map<string,string>();//Defining the property
carac.set("Color", "Blue"); // Setting key value
carac.set("age", "99") // Assigning another key value

An array is also initialized like this:

caracteristicas:Map<string, string>[];

Then the property is pushed inside the array in the following manner:

caracteristicas.push(carac);

In the HTML code, there is an iteration over the array to display the keys and values, achieved with the following code:

<tr *ngFor="let caracteristica of caracteristicas | keyvalue ; let i = index">
                <td>
                    {{caracteristica.key}}
                </td>
                <td>
                    {{caracteristica.value}}
                </td>
                <td>
                    <button (click)="quitarCaracteristica(i)">
                        <i class="fas fa-minus"></i>
                    </button>
                </td>
            </tr>

Despite using the key value pipe, the functionality does not work when running the application. Instead of displaying the keys and values, it shows something like: [object Map]. Any suggestions on how to properly showcase the keys and values are appreciated. The Angular version being utilized is 9. Thank you in advance.

Answer №1

When creating a map and placing it inside an array, remember that in your ngFor loop, you must first iterate over the array before accessing the map object.

Take a look at the code below, which you can adjust to fit your specific needs:

<tr *ngFor="let feature of features; let i = index">
<ng-container *ngFor="let mapItem of feature | keyvalue ">
                <td>
                    {{mapItem .key}}
                </td>
                <td>
                    {{mapItem .value}}
                </td>
         </ng-container>
                <td>
                    <button (click)="removeFeature(i)">
                        <i class="fas fa-minus"></i>
                    </button>
                </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

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

The fieldset css in PrimeNG differs from the website's original design

On my website, the appearance of the fieldset can be seen here: https://i.stack.imgur.com/TTS8s.jpg. I did not make any CSS changes that altered the fieldset. I am utilizing primeNG v7 and Angular 7. <p-fieldset legend="Toggleable" [toggleable]="true" ...

"Utilizing the Ionic side menu to activate a function in the view.ts file

In my app, there is a menu located in the main app.component.html <ion-app> <ion-split-pane contentId="main-content"> <ion-menu contentId="main-content" type="overlay"> <ion-content> ...

ValueError: The object is not a valid HTMLInputElement in Angular 5

I'm attempting to implement autocomplete functionality for an address using the Google Maps API in my application, but I keep encountering the "InvalidValueError: not an instance of HTMLInputElement" error. Here are the approaches I have experimented ...

What is the best way to retrieve the query results from Firestore?

After researching extensively, I have yet to find a solution to my issue with returning query results. Despite successfully executing the query, my client fails to receive the desired response. export const myFunction = functions.https.onCall((data, conte ...

Obtain a particular column from a JSON document using Angular 2

Currently, I am working on a project in Angular2 that requires the use of an online JSON file. I have utilized http.get to retrieve the file, but I only need the data from the second and third columns which contain the first name and last name. If you wan ...

What is the best way to eliminate all spaces in the Zod application?

After reading the Zod documentation, I found that trim only removes whitespace characters at the beginning and end. However, I am in need of a solution to remove all whitespace characters entirely. Here is an excerpt from my current setup (irrelevant code ...

Is Typescript familiar with the import -> require syntax, but unfamiliar with the require -> import syntax?

My code includes a simple file that utilizes the ES6 module loader: 1.ts import {foo} from "./2" foo('hello'); 2.ts function foo (a){console.log(a);}; export {foo} When the tsconfig is configured as follows: "module": "commonjs", We can o ...

Can React refs be safely accessed within a function wrapped with window.requestAnimationFrame?

My understanding of React and HTML rendering behavior is not complete, leaving me unsure about the possibility of a potential issue with React refs becoming null if accessed from a function wrapped in window.requestAnimationFrame. This function could be ...

My component fails to load using Angular Router even though the URL is correct

I have been experiencing an issue while trying to load my Angular component using the router. The component never appears on the screen and there are no error messages displayed. app-routing-module { path: '', redirectTo: '/home', ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Ensuring a precise data type in a class or object using TypeScript

I am familiar with Record and Pick, but I struggle to grasp their proper usage. My goal is to ensure that a class or object contains specific data types such as strings, Booleans, arrays, etc., while also requiring properties or fields of Function type. in ...

Filling in Table Sections and Rows with Data from an Array of Dictionary Entries

I'm currently working on populating a table from a model data class, storing my information as an array of dictionaries. Here's how it looks: var pupilSubjects = ["Tom":["English", "Geography", "History"], "Dick":["English", "Geography", "Physic ...

Issue with Javascript Date formatting as "dd-MMM-yyyy" in Internet Explorer

When retrieving data from the server side, I am encountering an issue with the date format dd-MMM-yyyy. if (new Date("02-MAY-2018").toDateString() == new Date(this.dob).toDateString()) { alert("No error"); } else { alert("error"); } The convers ...

Proper utilization of an interface with a literal object

I've been encountering some challenges with TypeScript. Let's say you have a literal object where the value is assigned using the spread operator: const defaultState = () => { return { profile: { id: '', displayName ...

Issue with Master Toggle functionality for checkbox within expanded rows of Mat-Table does not function correctly

I'm facing an issue with my multi-row expandable mat table grid where the master toggle for inner grid checkboxes is not working. Each row fetches data from different APIs on click, and I have a checkbox selection in every row for the inner grid. Int ...

Communication between parents and children is crucial for building strong relationships and providing validation

This question may have been asked in a complex manner before, but I will simplify it here. In my main component, I have a form tag and Submit Button. Within this component, there is a child component that contains an input field with a required attribute, ...

Issue with Angular 10 Web Worker: Unable to locate the main TypeScript configuration file 'tsconfig.base.json'

Every time I attempt to run: ng g web-worker canvas I consistently encounter the error message: Cannot find base TypeScript configuration file 'tsconfig.base.json'. After thorough examination of my files, it appears that I am indeed missing a ...

Exploring the functionality of test code within an rxjs subscription by utilizing the powerful technique of jasmine

My goal is to test the code within an observable subscription: function bar(someStream$: Observable<number>) { someStream$.pipe( map((x) => x + 3), ).subscribe((result) => { SomeService.someMethod(result) }) } I want to ensure t ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...