Angular 2 - A single form component for creating and editing

I am looking for good advice / best practice for reusing my form component.

Data Model:

class Contact { id?: String; name: String; } 
  • When creating a new Contact , of course, there is no id , so it is optional in the model.

  • When editing a Contact there is an id , but it is not editable and, therefore, is not part of the form.

Behavior:

The "Edit" and "Create" views must use the same @Component form because the available fields are the same and the validation restrictions are the same.

But both representations must have different actions. For instance. the Edit view should have a Delete and Reboot button, and, of course, the Save buttons of both views should behave differently (Create creates a POST request, Edit makes a PATCH request).

What I tried / Problems:

I created a ContactCreateComponent and a ContactEditComponent , which both have <contactForm [contact]="contact"></contactForm> in my template. And since there must be different buttons and actions in both views, I put the buttons in Create and Edit Components.

ContactFormComponent has the tags <form [formGroup]="form"> and <input formControlName="name"> .

Now I can’t understand how to pull form data from ContactFormComponent when the "Save" button is clicked.

Thoughts / Ideas:

I could define a FormGroup inside Create and Edit Components, and then pass the instance of the FormGroup to the form component via @Input . That way I could read / update / reset form data. But then I had to write the entire FormGroup definition and validators twice, although, in my opinion, this should remain inside the Form Component.

(I don't want to use two-way binding in the @Input property, because Contact is immutable)

Do you have any idea how to solve this?

+6
source share
1 answer

Now I can’t understand how to pull form data from ContactFormComponent when I click the Save button.

Create @ViewChild("form") form: ContactForm; Then you can call form.contact to get the edit contact.

In this case, I would not write 2 different components. Just check if the current form is being created or edited. Therefore, I will remain in the same form, after clicking the Save Create Form button, the Edit Form will become anyway.

+1
source

All Articles