Reputation: 24567
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?
Upvotes: 7
Views: 5558
Reputation: 6169
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.
Upvotes: 1