I'm looking for some good advice / best practice to reuse my Form Component.
class Contact {
id?: String;
name: String;
}
When creating a new Contact
there's of course no id
, that's why it's optional in the model.
When editing a Contact
there is an id
, but it's not editable and thus it's not part of the form.
The Edit and the Create view should use the same Form @Component
, because the available fields are the same, and validation constraints are the same, too.
But both views must have different actions. E.g. the Edit view must have a Delete and Reload button, and of course the Save buttons of both views must behave differently (Create makes a POST
request, Edit makes a PATCH
request).
I created a ContactCreateComponent
and a ContactEditComponent
, which both have the <contactForm [contact]="contact"></contactForm>
within their template. And because both views must have different buttons and actions, I did place the Buttons with in the Create and Edit Components.
The ContactFormComponent
has the <form [formGroup]="form">
and <input formControlName="name">
tags.
Now I can't figure out how to pull the form data out of the ContactFormComponent
when the Save Button is clicked.
I could define the FormGroup
within the Create and Edit Components and then pass the FormGroup
instance to the Form Component via @Input
. This way I could read / update / reset the Form Data. But then I had to write the whole FormGroup
definition and validators twice, though in my opinion this should stay within the Form Component.
(I don't want to use two-way binding on the @Input
property, because Contact
is immutable)
Do you have any idea how to solve this?
Angular provides two different approaches to handling user input through forms: reactive and template-driven.
In Angular, a reactive form is a FormGroup that is made up of FormControls. The FormBuilder is the class that is used to create both FormGroups and FormControls.
A FormArray aggregates the values of each child FormControl into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a FormArray is invalid, the entire array becomes invalid.
Now I can't figure out how to pull the form data out of the ContactFormComponent when the Save Button is clicked.
Create a @ViewChild("form") form: ContactForm;
Then you can call form.contact
to get the editing contact.
In this case I wouldn't write 2 different component. Just check if current form is creating or editing. So I would stay in the same form, after pushing Save
button an Create Form
will become Edit Form
anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With