Dividing a form into multiple components with validation

后端 未结 4 1251
闹比i
闹比i 2020-12-23 11:19

I want to create a single big form with angular 2. But I want to create this form with multiple components as the following example shows.

App component

4条回答
  •  感动是毒
    2020-12-23 11:51

    I would use a reactive form which works quite nicely, and as to your comment:

    Is there any other simple example for this one? Maybe the same example without loops

    I can give you an example. All you need to do, is to nest a FormGroup and pass that on to the child.

    Let's say your form looks like this, and you want to pass address formgroup to child:

    ngOnInit() {
      this.myForm = this.fb.group({
        name: [''],
        address: this.fb.group({ // create nested formgroup to pass to child
          street: [''],
          zip: ['']
        })
      })
    }
    

    Then in your parent, just pass the nested formgroup:

    In your child, use @Input for the nested formgroup:

    @Input() address: FormGroup;
    

    And in your template use [formGroup]:

    If you do not want to create an actual nested formgroup, you don't need to do that, you can just then pass the parent form to the child, so if your form looks like:

    this.myForm = this.fb.group({
      name: [''],
      street: [''],
      zip: ['']
    })
    

    you can pass whatever controls you want. Using the same example as above, we would only like to show street and zip, the child component stays the same, but the child tag in template would then look like:

    Here's a

    Demo of first option, here's the second Demo

    More info here about nested model-driven forms.

提交回复
热议问题