TypeScript Map Realtime Example
2 min readDec 20, 2022
Let’s take an example using Angular Reactive Form how you can use Map.
I am creating a Dynamic Reactive Form with showing errors using MAP. Let’s first create a form-element model.
form-element.ts
export class FormElement {
controlType: string;
label: string;
key: string;
errorMsg: string;
}
Now i will use the form-element to create dynamic fields of the form.
app.component.ts
import { Component } from '@angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
Validators,
} from '@angular/forms';
import { finalize } from 'rxjs';
import { FormElement } from './models/form-element';
import { SharedService } from './shared.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
form: FormGroup;
formElements: FormElement[] = [
{
controlType: 'textbox',
label: 'userid',
key: 'userid',
errorMsg: 'Userid Field is required',
},
{
controlType: 'passwrod',
label: 'password',
key: 'password',
errorMsg: 'Password Field is required',
},
];
submitted: boolean = false;
returnUrl: string;
validationMap = new Map<string, string>();
constructor(private sharedService: SharedService) {}
ngOnInit() {
const formGroupOptions = {};
for (const formElem of this.formElements) {
formGroupOptions[formElem.key] = new FormControl('', [
Validators.required,
]);
this.validationMap.set(formElem.key, formElem.errorMsg);
}
this.form = new FormGroup(formGroupOptions);
}
get f() {
return this.form.controls;
}
onSubmit() {
this.submitted = true;
if (this.form.invalid) {
return false;
}
console.log(this.f.userid.errors);
this.sharedService
.login(this.f.userid.value, this.f.password.value)
.pipe(finalize(() => this.validationMap.clear()))
.subscribe({
next: (data) => {
console.log('data => ', data);
},
error: (error) => {
console.log('error => ', error);
},
});
}
}
Here i have created a validationMap = new Map<string, string>() to set the errorMsg of form elements. The values will be store in validationMap like the following way :
{
userid => 'Userid Field is required',
password => 'Password Field is required'
}
Now you can display the error message using get function of Map of passing field-element key.
app.component.html
<div class="card">
<h4 class="card-header">Login</h4>
<div class="card-body">
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group" *ngFor="let formElem of formElements">
<label for="{{ formElem.label }}">{{ formElem.label }}</label>
<input
type="{{ formElem.controlType }}"
formControlName="{{ formElem.key }}"
class="form-control"
/>
<div class="error" *ngIf="submitted && f[formElem.key]['errors']">
{{ validationMap.get(formElem.key) }}
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Login</button>
<a routerLink="../register" class="btn btn-link">Register</a>
</div>
</form>
</div>
</div>