abin peter
abin peter

Reputation: 625

Creating Dynamic text-box in Angular 8 and binding the value to component while form submit

I am trying to add a Dynamic text box when a button is pressed.The dynamic text box is added successfully but unable to grab all the values (dynamically added textbox's value) while form submit.it always bind the last updated text box's value. Following is my code snippet

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>

Upvotes: 2

Views: 3385

Answers (1)

ViqMontana
ViqMontana

Reputation: 5688

I think you're confused as to how this should be working. Your contributeForm only has a single options field so you can only bind a single value to this...perhaps you'd like to make this an array.

Every time the add() functions is called, it'll get the current value for options. options is only bound to a single text box, which will be the last created one, i.e. the bottom text box. So each time you add a new options, the newest option text box will be bound to options.

Take a look at this StackBlitz and look at this console each time you add a new option.

Upvotes: 1

Related Questions