0

I am very new to LWC. And i am confused about why value is not coming in input text when i am going back to the same div(template).

<template>
<br/>
<br/>
<template if:true={showScreen1}>
    <c-child
        onscreenonenext={handleOnScreenNext}
    >
    </c-child>
</template>
<template if:true={showScreen2}>
    <c-screentwo
        onscreen2back={handleOnSreen2Back}>
    </c-screentwo>    
</template>
<br/>
<br/>
<br/>

playground link

Why value is not retaining in c-child component?? When i am going back? I know i can pass value from event to parent component and then pass it to the c-child component. But should not be working by default? Please help me this confusion.

Thanks, Manohar

1

When the component is removed from the DOM (via if:true), it is destroyed and the values within are lost. You'll want to pass the value back to the parent to save it for later.

I've updated your code to demonstrate this.

app.html

    <c-child value={value} onchange={updateValue}
        onscreenonenext={handleOnScreenNext}
    >

app.js

@track value;

updateValue(event) {
    this.value = event.detail.value;
}

child.html

<lightning-input 
    type="text" 
    label="Enter TEXT"
    onchange={handleChange}
    value={value}>

child.js

@api value;
handleChange(event) {
    this.dispatchEvent(new CustomEvent('change', { detail: {value: event.target.value}}));
}

Note that two-way binding doesn't exist in LWC, which is why we use an event to notify the parent that the value changed, and the parent then updates the value that will be sent back to the input element on the next render.

I recommend reading more about events in the documentation.

| improve this answer | |
1

c-child component lies between If condition, Therefore child component got reinitiated whenever condition matches.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.