4

I've created a Plunker to demonstrate the problem

https://embed.plnkr.co/pgu7szf9ySwZSitOA5dq/

If you remove #2, you see the #5 show up twice in the last two boxes. I cannot figure out why this is happening.

0

1 Answer 1

3

you should nested your FormArray in FormGroup like this:

export class AppComponent implements OnInit {
    public formG: FormGroup;
    public formArray: FormArray;

    constructor(private fb: FormBuilder) { }

    ngOnInit() {
      this.createForm(); 
    }


    createForm() {
      this.formArray = this.fb.array([
        this.fb.control(1),
        this.fb.control(2),
        this.fb.control(3),
        this.fb.control(4),
        this.fb.control(5),
      ]);
      this.formG = this.fb.group({
        farray: this.formArray
      });
      console.log(this.formArray);
    }

    addQuestion() {
      this.formArray.push(this.fb.control(''));
    }

    removeQuestion(i) {
      this.formArray.removeAt(i);
    }
}

And the template:

<div class="container" [formGroup]="formG">
  <div formArrayName="farray">
    <div class="row form-inline" *ngFor="let question of formArray.controls; let i = index">
      <textarea class="form-control" [formControlName]="i"></textarea>
      <button (click)="removeQuestion(i)" class="btn btn-secondary">Remove</button>
    </div>
  </div>
</div>
<button (click)="addQuestion()" class="btn btn-secondary">Add</button>

Form in action: https://embed.plnkr.co/hJ0NMmzGezjMzWfYufaV/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.