In Angular 5 (and later versions), you can create a dynamic key-value form by using Reactive Forms. Reactive Forms provide a way to manage and validate form inputs in a more structured and reactive manner.
To create a dynamic key-value form, you can follow these steps:
- Set up the Reactive Form in your component: Import the necessary modules and create a FormGroup instance to represent the form.
typescriptimport { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-key-value-form',
templateUrl: './key-value-form.component.html',
styleUrls: ['./key-value-form.component.css']
})
export class KeyValueFormComponent implements OnInit {
keyValueForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.keyValueForm = this.formBuilder.group({});
}
}
- Create a method to add and remove key-value pairs: You can have buttons to add or remove key-value pairs dynamically.
typescriptimport { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-key-value-form',
templateUrl: './key-value-form.component.html',
styleUrls: ['./key-value-form.component.css']
})
export class KeyValueFormComponent implements OnInit {
keyValueForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.keyValueForm = this.formBuilder.group({});
}
addKeyValuePair() {
this.keyValueForm.addControl('newKey', new FormControl('', Validators.required));
this.keyValueForm.addControl('newValue', new FormControl('', Validators.required));
}
removeKeyValuePair(key: string) {
this.keyValueForm.removeControl(key);
}
}
- Display the form in the template:
You can use the
formGroup
directive to bind the form to the template. UseformControlName
to bind specific controls to input fields.
html<form [formGroup]="keyValueForm">
<div *ngFor="let controlName of keyValueForm.controls | keyvalue">
<input *ngIf="controlName.key !== 'newValue'" [formControlName]="controlName.key" placeholder="Key">
<input *ngIf="controlName.key !== 'newKey'" [formControlName]="controlName.key" placeholder="Value">
<button *ngIf="controlName.key === 'newValue'" type="button" (click)="addKeyValuePair()">Add</button>
<button *ngIf="controlName.key !== 'newKey'" type="button" (click)="removeKeyValuePair(controlName.key)">Remove</button>
</div>
</form>
The code above will generate a form that allows you to add and remove key-value pairs dynamically. When you click the "Add" button, a new pair of input fields will be added, and when you click the "Remove" button next to an existing key-value pair, it will be removed from the form.
Keep in mind that Angular 5 is relatively old, and the latest version of Angular at the time of writing this (2023) is Angular 12. It is recommended to use a more recent version of Angular for new projects, as it will have better features, improvements, and security updates.