Angular: composite ControlValueAccessor to implement nested form

后端 未结 2 1146
粉色の甜心
粉色の甜心 2020-11-28 14:21

Composition of ControlValueAccessor to implement nested form is introduced in an Angular Connect 2017 presentation.

https://docs.google.com/presentation/d/e/2PACX-1v

相关标签:
2条回答
  • 2020-11-28 14:30

    Couple issues, on your AppComponent change your FormBuilder to:

    this.form = fb.group({
      name: 'foo bar',
      address: fb.control({ //Not using FormGroup
        city: 'baz',
        town: 'qux',
      })
    });
    

    On your AddressFormComponent you need to initialize your FormGroup like so:

    form: FormGroup = new FormGroup({
        city: new FormControl,
        town: new FormControl
    });
    

    Here's the fork of your sample: https://stackblitz.com/edit/angular-np38bi

    0 讨论(0)
  • 2020-11-28 14:44

    We (at work) encountered that issue and tried different things for months: How to properly deal with nested forms.

    Indeed, ControlValueAccessor seems to be the way to go but we found it very verbose and it was quite long to build nested forms. As we're using that pattern a lot within our app, we've ended up spending some time to investigate and try to come up with a better solution. We called it ngx-sub-form and it's a repo available on NPM (+ source code on Github).

    Basically, to create a sub form all you have to do is extends a class we provide and also pass your FormControls. That's it.

    We've updated our codebase to use it and we're definitely happy about it so you may want to give a try and see how it goes for you :)

    Everything is explained in the README on github.

    PS: We also have a full demo running here https://cloudnc.github.io/ngx-sub-form

    0 讨论(0)
提交回复
热议问题