What are the best techniques for implementing a Map() within [(ngModel)]?

I'm attempting to insert a specific value into a map at a designated key.

My approach involves using ngFor to iterate through an array. The item obtained in each iteration should serve as the key for the map, while the user enters the corresponding value.

NOTE: The variable userInputValue is currently non-existent. This is precisely what I am questioning: How can I obtain the userInputValue to assign it to the map? Hopefully my explanation makes sense...

The item represents any string, such as "Name", and userInputValue would be whatever the user inputs into the input field. How can I retrieve this value in this scenario?

In my Component.html

<form *ngFor="let item of myStringArray">
    <input [(ngModel)]="map.set(item, userInputValue)">
</form>

In my Component.ts

public map = new Map<string, string>();

public myMethod() {
    this.stringInputs.forEach((item) => {
       this.entry.roomSizeSQM = this.map.get(item);
    });
}

Is it feasible to utilize a Map in this manner? If so, how can I do it correctly, and if not, are there alternative approaches I could take to achieve this goal (aside from creating my own class)?

Currently, my solution involves delimiter splitting and appears as follows:

// the string might be something like: "Name;34"

this.finalInputWithContext.forEach((item) => {

  if (item.split(";")[0] === "Name") {
    console.log(item.split(";")[1]); // will display 34
  }

});

This method works fine, but I have been advised to use a Map instead...

Answer №1

To effectively handle [(ngModel)], you can break it down into two separate parts, [ngModel] and (ngModelChange), and then utilize the appropriate method from the Map object for each part. The user-inputted value can be accessed through the $event parameter within the ngModelChange event.

<form *ngFor="let item of myStringArray">
  <input name="value" [ngModel]="map.get(item)" (ngModelChange)="map.set(item, $event)">
</form>

Check out a demonstration on this stackblitz link.

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

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

How can I make TypeScript mimic the ability of JavaScript object wrappers to determine whether a primitive value has a particular "property"?

When using XMLValidator, the return value of .validate function can be either true or ValidationError, but this may not be entirely accurate (please refer to my update). The ValidationError object includes an err property. validate( xmlData: string, opti ...

retrieve the value from the angularfire database list subscription

I need help with calculating the total sum of 'amount' values in my 'expenses' list. Take a look at my database: https://i.sstatic.net/lN3OQ.gif Although the log inside the subscribe function correctly shows a total of 1700, I'm ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Encountered a problem while trying to install angular/cli via the

Encountering errors while attempting to install Angular/CLI using the npm command line. The error message displayed is as follows: npm ERR! Darwin 16.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g" "@angular/cli" npm ERR! node ...

Confirm that a new class has been assigned to an element

I'm having trouble creating a unit test for a Vue.js component where I need to check if a specific CSS class is added to the template. Below is the template code: <template> <div id="item-list" class="item-list"> <table id="item ...

retrieve all users from the mongodb database

How can I modify this function to retrieve all users? I am currently in the process of learning async await and struggling with understanding how to access the request body. Here's my function: export const get: Operation = async ( req: express.Req ...

Is there a way to restrict the use of `any` exclusively to the tests folder when working with biome

I am currently working on a TypeScript repository that has both a 'src' and 'tests' folder. My goal is to set up biome for this project. Specifically, I want to enforce strict linting rules in the 'src' folder, but allow the u ...

What steps should be taken to combine an Angular 4 application with a Spring Boot framework?

Seeking advice on integrating an Angular 4 client app with a Java Spring application that operates on http://localhost:8080/ and provides Rest endpoints. My objective is to access the Angular app from a URL such as http://localhost:8080/adminisitration. An ...

Reorganize mat-table rows using Angular Material's drag-and-drop feature

One of the new features that came with Angular 7 is the powerful DragDropModule: https://material.angular.io/cdk/drag-drop/examples The documentation covers rearranging items in lists and transferring them between different lists, but it doesn't ment ...

Angular and the Client IP Address

I am trying to retrieve the client's local IP address within an internal network using Angular. This data will be sent to an IP address within the network without requiring authorization. I have searched extensively online but have only found methods ...

Using two indexes in ngFor can result in unexpected changes to the values being displayed

I am currently working on printing checkboxes and facing an issue with initializing the id and name attributes using ngFor. The values I'm getting are incorrect. Let's consider 2 arrays (or n arrays retrieved from a database): animal = 'do ...

Why doesn't TypeScript automatically determine the prop type when Generics are used?

Below is the code snippet: interface MyInterface { a: { b: { c: "c"; }; }; } type ParentProps = keyof MyInterface type ChildProps<ParentProp extends ParentProps> = keyof MyInterface[ParentProp] type GrandChildType< ...

Is there a way to prevent the virtual keyboard from covering up input fields on a webview?

I am currently dealing with an issue on my Genero web-app where the webview of an Angular app is not scrolling under an input when it gets the focus. This makes it difficult for users to see what they are typing. Interestingly, loading the page in a regula ...

Creating a TypeScript type that allows for the possibility of being undefined

I have a project where I am converting Scala code to TypeScript. In Scala, there is a predefined type called Option which can either be a specific type or undefined. In TypeScript, we usually represent it like this: var myVar : MyType | undefined = await ...

Can you tell me the significance of the constant variable isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]`?

const isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]` This function is all about determining types, but the arrows used in the syntax are confusing to me. I'm not sure what each arrow s ...

What methods can be implemented to ensure uniform usage of a single library version among all developers?

Our team utilizes Angular and Visual Studio Code for development, while GitHub serves as our code repository. While this setup has been effective, we recently encountered an issue where one developer had a different version of a particular library. This di ...

What steps can be taken to resolve a serve error specifically in a production environment caused by the absence of package

How do I resolve the following error: > ng "serve" "0.0.0.0" "--poll=2500" "--disable-host-check" "--prod=true" WARNING Running a server with --disable-host-check is a security risk. See https://medium.com/webpack/webpack-dev-server-middleware-securit ...

Excessive spacing issue in dropdown menu when using VirtualScroll feature in ng-select component for Angular

https://i.sstatic.net/u1BMB.png There is an issue with extra space appearing in the ng-select dropdown when using the virtuallScroll property set to true. Here is a reproducible example: https://stackblitz.com/edit/angular-uuvic8?file=styles.css ...