Creating dynamic form fields in Angular is very easy we just have to use formArrayName & FormArray service it will allow us to create dynamic form fields.
<div class="group-gap" formArrayName="addDynamicElement">
<h5 class="mb-3">Add Super Powers</h5>
<div class="mb-3">
<button type="button" class="btn btn-sm btn-success mb-3 btn-block" (click)="addSuperPowers()">Add Powers</button>
<ul class="subjectList">
<li *ngFor="let item of addDynamicElement.controls; let i = index">
<input type="text" class="form-control" [formControlName]="i">
</li>
</ul>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-danger btn-lg btn-block">Create Superhero</button>
</div>
app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormArray } from "@angular/forms";
@Component({
//...
})
export class AppComponent {
constructor(public fb: FormBuilder) {}
registrationForm = this.fb.group({
addDynamicElement: this.fb.array([])
})
get addDynamicElement() {
return this.registrationForm.get('addDynamicElement') as FormArray
}
addSuperPowers() {
this.addDynamicElement.push(this.fb.control(''))
}
}
No comments:
Post a Comment