0
votes

I'm using reactive forms and I would like to add/remove a field of my form when I click in a button, like this example (its a prototipe of my desire):

Mock

Thats mean, when I click in the + button, another select with the same field will appear. When I click in -, the field will be removed

1

1 Answers

2
votes

From https://www.udemy.com/the-complete-guide-to-angular-2/learn/v4/overview

You can follow the same pattern

form.html

<div formArrayName="hobbies">
          <h4>Your Hobbies</h4>
          <button
            class="btn btn-default"
            type="button"
            (click)="onAddHobby()">Add Hobby</button>
          <div
            class="form-group"
            *ngFor="let hobbyControl of signupForm.get('hobbies').controls; let i = index">
            <input type="text" class="form-control" [formControlName]="i">
          </div>
        </div>

form.ts

this.signupForm = new FormGroup({
      'userData': new FormGroup({
        'username': new FormControl(null, [Validators.required, this.forbiddenNames.bind(this)]),
        'email': new FormControl(null, [Validators.required, Validators.email], this.forbiddenEmails)
      }),
      'gender': new FormControl('male'),
      'hobbies': new FormArray([])
    });

onAddHobby() {
    const control = new FormControl(null, Validators.required);
    (<FormArray>this.signupForm.get('hobbies')).push(control);
  }