Utilizing the MapToIterable Angular Pipe with TypeScript

Exploring the implementation of a pipe in Angular. Discovered that ngFor doesn't work with maps, prompting further research to find a solution. It seems that future features may address this issue, but for now, utilizing a mapToIterable pipe is the recommended workaround.

The code snippet is as follows:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'mapToIterable'
})
export class MapToIterablePipe implements PipeTransform  {
  transform(map: Map<string, Object>, args: any = []): any {
    const a: any[] = [];
    console.log(map.keys());  // <- expected outcome
    for (const k in map) {
      if (map.has(k)) {
        console.log("hello");  // <- not executed
        console.log(k);
        a.push({key: k, val: map.get(k)});
      }
    }
    console.log(a); // <- always empty
    return a;
  }
}

export const MAPTOITERABLE_PROVIDERS = [
  MapToIterablePipe
];

Although map.keys() returns the correct keys, other parts of the code are not functioning as intended.

Any advice on troubleshooting why the loop isn't populating the array correctly?

Answer №1

Map 'keys' are different from object keys and cannot be accessed using Object.keys() or the in operator.

When using map.keys(), it returns an iterable, so you should iterate over it like this:

for (const key of Array.from(map.keys())) {
  // no need for this check
  // if (map.has(k)) {
  ...
}

In TypeScript 3.0 with the downlevelIteration option,

for (const key of map.keys()) { ... }

Alternatively,

const a: any[] = Array.from(map.entries()).map(([key, val]) => ({ key, val }));

Due to how TypeScript handles spread operator in versions 2.2 and below, [...iterable] may not function the same as Array.from(iterable).

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 is the best way to incorporate Firebase into an Angular 2 TypeScript application without relying on AngularFire?

What is the best way to integrate Firebase into an Angular 2 TypeScript application without relying on AngularFire? I have a simple Angular 2 application and I am looking to incorporate Firebase into it. ...

Creating a Docker Image for Node.Js Using Bazel

Reason Behind the Need I am diving into the Bazel world and struggling to find comprehensive references on constructing Docker images for Node.js. My focus lies on a Typescript-based Node.js application that relies on two other Typescript packages. My ul ...

Experimenting with TypeScript Single File Component to test vue3's computed properties

Currently, I am in the process of creating a test using vitest to validate a computed property within a vue3 component that is implemented with script setup. Let's consider a straightforward component: // simple.vue <script lang="ts" set ...

Using onDoubleClick with MUI TextField: A Quick Guide

Whenever the user double clicks the input field, I would like to automatically select the text. I have created a function for this specific action: export const selectText = ( event: React.MouseEvent<HTMLInputElement | HTMLTextAreaElement, MouseEvent& ...

I am facing an issue with toastr in Angular 8 as it is not functioning properly and showing me errors

I encountered an issue while trying to use Angular 8 toastr. The error message in the console is as follows: ngx-toastr.js:264 Uncaught TypeError: Object(...) is not a function at ngx-toastr.js:264 at Module../node_modules/ngx-toastr/fesm5/ngx-toastr.js ( ...

Retrieve a specific category within a method and then output the entire entity post adjustments

I need to sanitize the email in my user object before pushing it to my sqlite database. This is necessary during both user creation and updates. Here's what I have so far: export const addUser = (user: CreateUser) => { db.prepare(sqlInsertUser).r ...

Access Select without needing to click on the child component

I am curious to learn how to open a Select from blueprint without relying on the click method of the child component used for rendering the select. <UserSelect items={allUsers} popoverProps={{ minimal: false }} noResults={<MenuItem disabled={ ...

Integrating a title field into every p-column with ng-template

I am exploring ng-templates for the first time. I have managed to customize each column to display names accurately, but I am encountering an issue. I would like to incorporate a title field in order to show a tooltip with the full name when hovering over ...

Encountering "Cannot write file" errors in VSCode after adding tsconfig exclude?

When I insert the exclude block into my tsconfig.json file like this: "exclude": ["angular-package-format-workspace"] I encounter the following errors in VSCode. These errors disappear once I remove the exclude block (However, the intended exclusion fu ...

The ag-Grid cellDoubleClicked event seems to be triggered twice when the cell is double clicked quickly, but functions correctly when double clicking at a slower

Currently, I am facing an issue in my Angular 8 project while using Ag-grid. The problem arises when I try to handle the double click event in ag-grid. Whenever the cellDoubleClicked event is triggered, a method is called twice if I quickly double click on ...

Creating multiple routes within a single component in Angular without triggering unnecessary redraws

Within the ChildComponent, there is a reactive form that allows for data entry. Upon saving the filled form, the route should be updated by appending an id to the current route. Currently, when saving, the component renders twice and causes screen flicke ...

What is the importance of specifying a language version when parsing a TypeScript source file?

Currently, we are utilizing the public API to analyze TypeScript files in this manner: ts.createSourceFile( file.name, file.textContent, languageVersion, /*setParentNodes*/ true); Something that has caught our attention is the significanc ...

Hiding a div after three clicks using HTML

What is the best way to hide a div tag containing an input tag after clicking on the input tag three times using HTML and angular? ...

Unit tests in Jasmine disable dispatchers when NGXS store.reset is invoked

I am facing a challenge with an unusual behavior during the unit testing of my NGXS store using Jasmine. Specifically, I am encountering issues when trying to test the DeleteAlerts action : @Action(DeleteAlerts) deleteAlerts(ctx: StateContext<Alert ...

Using observable object fields as query parameters in Firestore allows for dynamic filtering and retrieval

I have two separate services in my Angular project: an Auth service and a query service. The Auth service handles user authentication by managing the login process and observing changes to the user object. import {Injectable} from '@angular/core&apo ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

Does adding a callback to object.ngOnDestroy() replace its internal onDestroy() method?

I'm enhancing the drag and drop feature in Angular <div cdkDropList appImprovedDropList> <div cdkDrag>item 1</div> <div cdkDrag>item 2</div> <div cdkDrag>item 3</div> </div> The directive appImpro ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Troubleshooting a Docker EPERM issue while attempting to compile an Angular application within a container

Our team is currently in the process of containerizing our existing stack using Docker and Docker Compose. This is a simplified version of our Docker Compose file with the relevant services: version: '3.8' services: #FO angularproject: c ...

How can I retrieve distance data from the Google Maps API within an Angular service?

I am currently working on implementing the JavaScript version of the Google Maps API in order to resolve a CORS issue that I encountered with the regular API. Specifically, I am looking to calculate the distance and time between two destinations. How can I ...