1

I am a bit confused with angular's form group and form array. I know you can nest form arrays in form groups but can a form array exists on its own? Basically I need the entire form to be an array that I can push "base" controls to, OR, insert controls at certain positions depending on selections from a dropdown. for example

  1. Name (text field)
  2. Phone (text field)
  3. Payment schedule (dropdown w/ values of weekly, monthly, yearly)
  4. Address (text field)

If weekly is selected from the payment schedule dropdown I need to show a new input, lets say its called "day of week", in between payment and address fields.

This is the part that im struggling with. I've basically built out this (https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2)tutorial but can't wrap my head around how to add field in between each other if the whole form is not a form array, which I can't seem to do.

question-control.service.ts (from angular docs. see: https://angular.io/guide/dynamic-form)

questions.forEach(question => {

  group[question.key] = question.required ?
    new FormControl(question.value || '', [Validators.required, Validators.minLength(question.minLength)]) :
    new FormControl(question.value || '');
});

return new FormGroup(group);
4
  • So what have you tried and what piece of code are you struggling with? :) Commented Feb 20, 2018 at 17:43
  • 1
    just make the entire form an form group.But what you are describing, you could section pieces of the form using form groups and showing or hiding based on other form inputs. Commented Feb 20, 2018 at 17:53
  • 1
    @Anthony, you needn't use a formArray. You create a formGroup with all the necessary fields. then you hide a field or not (e.g. using *ngIf) according the values of another fields. but you don't need a formArray Commented Feb 20, 2018 at 18:08
  • I anticipate there being validation issues if a field that is set as required is hidden. See the code I added to my question. Would the solution be to have them not required and only set as required if that section is currently being shown? @Eliseo Commented Feb 20, 2018 at 18:17

1 Answer 1

1

I think you've approached this in an incorrect way. You don't need to use a form array whatsoever, it's making life a lot more complicated than it needs to be. Just make a form with ALL the fields that the form will use. Then put onchange methods on controls which need to amend the validity of other controls.

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.