Sir Jay
Sir Jay

Reputation: 59

How to actually Inject Data to CmsComponentData in Spartacus Storefront?

I need to prepare some dummy data on spartacus storefront. I am extending the BannerComponent and want to use this component inside several different other custom Components. But I don't understand how data is actually injected to the property public component: CmsComponentData

I already read about that part here https://sap.github.io/spartacus-docs/customizing-cms-components/

But this section is not really explaining how the data is actually injected to "data$". I was looking for some classic "new CmsComponentData()" approach where I can just reference a local image-path. Probably that's not the way to go...

In the spartacus default Source Base, I don't see any occurrence of "cx-banner" being used in any HTML File. But this is exactly what (I think) I need to do in my custom Components (containers that hold both paragraphs AND the banner). If I reference my new < custom-cx-banner > inside an HTML template, it won't bare any data. How do I inject it?

Thanks for your time.

Upvotes: 0

Views: 1206

Answers (1)

L Tiger
L Tiger

Reputation: 581

There are multiple ways to pass data to components.

You mention the CmsComponentData. This is a stream of data only available in CMS components. The data within this object is the one received from OCC. It is available to use in all CMS components even custom as long as they receive data.

You also mentioned you do not see any occurrence of cx-banner that is correct as the banner component is a CMS component. This means that it is mapped to a backend CMS component and dynamically placed in the DOM by Spartacus. When Spartacus receives the page map from the pages request it will dynamically render these components according to the CMS map.You can find more information about it here: https://sap.github.io/spartacus-docs/banner-component/#cms-component-binding.

Now if what you are looking for is a component that will be referenced in other components, a CMS component is not be the way to go. As you mentioned placing a <cx-banner> in the DOM will not give it data. You have three options that would allow you to do what you want.

  1. Use the CMS

You can place the banner where you want it in SmartEdit and give it some data there.

  1. Fetch the data in the component

Basically, in your component you should inject the a service that allows you to fetch the data you need. For example, the add-to-cart.component injects the CurrentProductService and gets the product data from there.

  1. Pass the data to the component via input

You can find more details here. Basically, if the parent component already contains the data the child requires, it can pass the data to the child via input.

You might also be able to combine these solutions.

Upvotes: 1

Related Questions