Topic: how to display a list of fields and add fields dynamically
herve pro asked 3 years ago
Hello, I would like to display a list of input fields with an ngFor loop, and have the possibility to add a field or remove fields. I haven't found any documentation on how to name fields or how to add some thank you for your help
Arkadiusz Idzikowski staff answered 3 years ago
You need to create an array of objects that contain parameters you want to include in the inputs. To add/remove input, you just need to add/remove those objects and Angular will update the app view automatically. Here is an example:
HTML:
<div class="md-form" *ngFor="let input of inputs">
<input mdbInput type="text" id="input.id" class="form-control">
<label for="input.id" class="">{{ input.label }}</label>
</div>
<button (click)="add('test-4', 'Example label 4')" type="button" mdbBtn color="primary" mdbWavesEffect>Add input</button>
<button (click)="remove(inputs.length - 1)" type="button" mdbBtn color="primary" mdbWavesEffect>Remove input</button>
TS:
inputs = [
{ id: 'test-1', label: 'Example label 1'},
{ id: 'test-2', label: 'Example label 2'},
{ id: 'test-3', label: 'Example label 3'}
];
add(id: string, label: string): void {
this.inputs.push({ id: id, label: label });
}
remove(index: number): void {
this.inputs.splice(index, 1);
}
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Pro
- Premium support: No
- Technology: MDB Angular
- MDB Version: 8.8.2
- Device: pc
- Browser: chrome
- OS: windows 10
- Provided sample code: No
- Provided link: No