Lightning Web Components – Pass Value to Flow from LWC Instantly

lightning-web-componentsvisual-workflow

I have a super simple Lightning Web component with input field and a button. The idea is to send the input field value to flow using FlowAttributeChangeEvent of Flow Support module in lwc.

What is happening at the moment?

The button click is firing FlowAttributeChangeEvent and value is being passed to a variable in Flow when we go to next screen.

What i am looking?

I want to assign the value passed from lwc to flow in the same screen.

flowAndLwcDataExchange.html

<template>
    <lightning-input label="Value To Pass To Flow" value={_valueToFlow} onchange={handleChange}></lightning-input>
    <lightning-button label="pass value" onclick={handleSendValueToFlow}></lightning-button>
</template>

flowAndLwcDataExchange.js

import { LightningElement, api, track } from 'lwc';
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
export default class FlowAndLwcDataExchange extends LightningElement {
    @track _valueToFlow;

    @api
    get valueToFlow() {
        return this._valueToFlow;
    }
    set valueToFlow(val) {
        console.log('getter', val);
        this._valueToFlow = val;
    }

    handleSendValueToFlow() {
        const attributeChangeEvent = new FlowAttributeChangeEvent(
            'valueToFlow',
            this._valueToFlow
        );
        this.dispatchEvent(attributeChangeEvent);
    }

    handleChange(event) {
        console.log(this._valueToFlow);
        this._valueToFlow = event.target.value;

    }
}

flowAndLwcDataExchange.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__FlowScreen</target>
    </targets>

    <targetConfigs>
        <targetConfig targets="lightning__FlowScreen">
            <property name="valueToFlow" type="String" label="Pass Value To Flow" role="outputOnly"/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Flow

enter image description here

Best Answer

It sounds like you want to use the output of your screen component to affect something else on the same screen.

Today, that's not really possible. The Flow team is building a new reactive capability into screen components, which is previewed here. Salesforce hopes to make that available in beta form in Spring '23. With that implementation, you will not have to fire any events yourself. Any value you assign to an output-enabled attribute in your component will automatically be available to all of the inputs of all of the components on the screen, and will cause any components that consume that output to rerender.

If you absolutely need to solve this today, you could consider creating a wrapper component that wraps both of your components and mediates the event passing.

Related Topic