Dividing a form into multiple components with validation

后端 未结 4 1244
闹比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条回答
  •  梦毁少年i
    2020-12-23 12:08

    From my experience, this kind of form field composition is hard to make with template-driven forms. The fields embedded in your address component don't get registered in the form (NgForm.controls object), so they are not considered when validating the form.

    • You can create a ControlValueAccessor component (that accepts ngModel attribute) with all validations, but then it's hard to display validation errors and propagate changes (address is considered as a single form field with a complex value).
    • You could probably pass the form reference into the Address component and register your inner controls in it, but I haven't tried that and seems to be an odd approach (I haven't seen it anywhere).
    • You can switch to reactive forms (instead of template driven), pass a form group object (representing an address) into the Address component, keeping the validation in your form definition. You can see an example here https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2

提交回复
热议问题