I'm trying to get a specific value into a map at a specific key.
In my code I use ngFor
to loop through the array. The item I get in each iteration should be the key value of the map, while the user input the corresponding value.
IMPORTANT: The variable userInputValue
doesn't exist. That's the point of my Question: How do I get the userInputValue
so that I can apply it to the map?
I hope you can undertsand what I mean..
The item
is any string for example "Name"
and userInputValue
would be whatever the user has typed into the input field
, how do I get the latter in this case?
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.eintrag.raumgroesseQM = this.map.get(item);
});
}
Is it possible to use Map in such a fashion, if yes, how can I do it correctly and if no, are there any other ways I could reach this goal (except for making my own class of course)?
My current approach uses delimiter splitting and looks like this:
// the string would be something like: "Name;34"
this.finalInputWithContext.forEach((item) => {
if (item.split(";")[0] === "Name") {
concole.log(item.split(";")[1]); // will print 34
}
});
This solution works too of course, however I was told to use a Map instead..
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
NgModule: Module used by NgModel is: FormsModule.
Angular NgModel is an inbuilt directive that creates a FormControl instance from the domain model and binds it to a form control element. The ngmodel directive binds the value of HTML controls (input, select, textarea) to application data. We can merely achieve it in the component element and the HTML element both.
The ngmodel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package into your Angular module.
You can separate [(ngModel)]
in its two parts, [ngModel]
and (ngModelChange)
, and call the appropriate Map
method in each part. The value typed by the user is given by the $event
parameter of the ngModelChange
event.
<form *ngFor="let item of myStringArray">
<input name="value" [ngModel]="map.get(item)" (ngModelChange)="map.set(item, $event)">
</form>
See this stackblitz for a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With