1

I've built a form that takes 4 attributes of a person:

firstName, lastName, email, mobile

That form can be used in many places in the application. All the tutorials I've seen show reusable components but only as child components of a related parent. For example:

/customers <- renders a list of customers, select one and
/customers/1 <- renders a customer detail, with a customer form

But what if I also have:

/contacts <- renders a list of contacts
/contacts/1 <- renders a detail, with a contact form

But the Customer and Contact form are identical, have the same four fields/controls (but obviously will save/update to different api).

Is it possible to create a generic 'person' form that can subscribe to a service - when the form is placed on customer page, inject the customer service and when placed on the contact page, inject the contact service.

Then the form can save the changed data back to the correct service.

I've not seen any example of this kind of form reuse. Is this possible?

rmcsharry
  • 5,363
  • 6
  • 65
  • 108

1 Answers1

2

If I am understanding your question properly, then what you could ask similarly is: Can I conditionally inject services? The answer is yes. You can do this is several ways.

One way is to extend the component like THIS. But that is a bit ugly for me.

The way that I have solved this in the past is to inject both services into your component, but conditionally subscribe() to them. In your case you can do this by reading the route params for contacts or customers.

Also, depending on your implementation, you can consider making the form a separate component and passing in the customer or contact by way of the @Input decorator.

Community
  • 1
  • 1
Nate May
  • 3,814
  • 7
  • 33
  • 86