Just changing the flow-api-name
attribute will not change the flow, you need to completely rerender the lightning-flow
component.
Here is the code snippet that I had written for my blog post: Call Lightning Screen Flow inside Lwc Component
, last year. You can find the full code in this git repo: call-flow-in-lwc
HTML
<template>
<lightning-card
variant="Narrow"
title="Flow in Lwc"
icon-name="standard:account"
>
<div class="slds-var-p-horizontal_small">
<!-- Dynamically select the flow to run -->
<lightning-combobox
name="objectType"
label="Select Object To Run Flow"
value={flowApiName}
placeholder="Select Object"
options={options}
onchange={handleChangeFlow}
></lightning-combobox>
<!-- Invoke a Screen flow in LWC -->
<lightning-flow
if:true={showFlow}
flow-api-name={flowApiName}
flow-input-variables={flowInputVariables}
onstatuschange={handleFlowStatusChange}
>
</lightning-flow>
</div>
<p slot="footer">Card Footer</p>
</lightning-card>
</template>
JS
import { LightningElement } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
const timeout = 10;
export default class FlowInLwc extends LightningElement {
flowApiName = "Create_Lead_Flow";
showFlow = true;
// Setting flow input variables,
// hard coded only for demo purpose
get flowInputVariables() {
if (this.flowApiName === "Create_Lead_Flow") {
return [
{
name: "companyName",
type: "String",
value: "Burlington Textiles Corp of America"
}
];
}
// Create_Contact_Flow
return [
{
name: "accountId",
type: "String",
value: "001B000001QzX1wIAF"
}
];
}
options = [
{ label: "Create Contact", value: "Create_Contact_Flow" },
{ label: "Create Lead", value: "Create_Lead_Flow" }
];
handleChangeFlow(event) {
clearTimeout(this.timer);
this.showFlow = false;
this.flowApiName = event.target.value;
// eslint-disable-next-line @lwc/lwc/no-async-operation
this.timer = setTimeout(() => {
this.showFlow = true;
}, timeout);
}
handleFlowStatusChange(event) {
console.log("flow status", event.detail.status);
if (event.detail.status === "FINISHED") {
this.dispatchEvent(
new ShowToastEvent({
title: "Success",
message: "Flow Finished Successfully",
variant: "success"
})
);
}
}
}
FURTHER EXPLANATION -
So when we use if:true with a false value it removes the component from the browser window and vice-versa. But any such changes to the linked attributes are consolidated in a single event. so if you hide/show the component multiple times in the same function that will only take effect based on the last assigned value only and ignore any intermittent changes because the component is rendered after the event handler execution is finished.
So if the event handler changes the value from true to false and then true, lwc-engine would not notice that change that is why I created a delay and a new transaction apparently. I hope that helps. you can observe that inside a browser if done with the inspector on.