When I attempt to add a dynamic text box after clicking a button, the text box is successfully added. However, I am facing an issue where I am unable to retrieve all the values (values of dynamically added text boxes) when the form is submitted. It seems to only bind the value of the last updated text box. Below is a snippet of my code:
contribute.component.ts
export class ContributeComponent implements OnInit {
categories = [];
contribute = {};
private options = [{ value: '' }];
private contributeForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.contributeForm = this.formBuilder.group({
question: new FormControl(),
category: new FormControl(),
options: new FormControl()
});
add() {
this.options.push({ value: this.contributeForm.controls.options.value });
}
And in my HTML file, contribute.component.html
<form [formGroup]="contributeForm" (ngSubmit)="onSubmit(contributeForm.value)">
<div class="form-group">
<label class="control-label col-sm-2" for="message">Options:</label>
<div class="col-sm-10 inputGroupContainer">
<div *ngFor="let option of options; let in=index" class="spacer">
<div class="input-group">
<span class="input-group-addon">Option {{in+1}}</span>
<input type="text" class="form-control" rows="4" placeholder="Type your option here"
formControlName="options" name="option" [value]="options[in].value"/>
</div>
</div>
</div>
<div class="row"></div>
<div class="col-sm-12 pull-right">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<button class="btn btn-warning" type="button" (click)="add()">Add option <span
class="glyphicon glyphicon-send"></span>
</button>
</div>
<div class="col-sm-4"></div>
</div>
</div>