Dynamic Interactions on Lightning App Page
Salesforce provides multiple ways to communicate between components which are not related to each other. E.g. pubsub module or Lightning Message Service. For the components which are related to each other, one can use public properties of component in addition pubsub module or Lightning Message Service. However, it was not possible to use the public properties with unelated components on lightning app page.
Recently, Salesforce has introduced dynamic interactions which lets you use public properties of components with unrelated components with some manual configurations. Lets understand how dynamic interactions can be used in lightning app page.
NOTE: Dynamic Interactions are supported only on lightning app pages with limited activity between components
What it takes to use dynamic interactions?
A components which defines the event schema and publish the event, a component with public properties and few configurations on lightning app page. Lets understand each and see how we can use dynamic interactions.
Defining event schema:
Event schema is defined in js-meta file of lwc. Under targetConfig with targets attribute set as lightning__AppPage, event tag can be added with schema in json object format.
<targetConfigs> <targetConfig targets="lightning__AppPage"> <event name="infoAdded" label="Info Added" description="This event fires when an info is added and publish button is clicked."> <schema> { "type": "object", "properties": { "firstName": { "type": "string", "title": "First Name", "description": "Please enter your first name." }, "lastName": { "type": "string", "title": "Last Name", "description": "Please enter your last name." } } } </schema> </event> </targetConfig> </targetConfigs>
Publishing event:
Identify the interaction which needs to be handled and add the respective event listeners. CustomEvent object instance and dispatchEvent method are required to publish the event like any other event publishing.
handlePublishClick() { const firstName = this.firstName; const lastName = this.lastName; this.dispatchEvent( new CustomEvent("infoAdded", { detail: { lastName, firstName } }) ); }
Important things to remember when publishing dynamic interaction event
- It is mandatory that the events properties names match the names provided in event schema
- Sequence of properties does not matter
- Event detail should be set in above format only. Interaction won't work if json object format is used e.g. "lastName": this.lastName
- It s not required that the properties in publisher components are public