How do you change the value of a lightning-input-field in javascript?

I have a simple component that creates a record using lightning-record-edit-form. After the record is created, I want to clear the values of the lightning-input-field components. I have tried a few different ways, and none seem to work. The same code applied to a lightning-input does work.

example template

<template>
    <lightning-card title="bug sample">
        <lightning-record-edit-form id="form" object-api-name="Account" onsubmit={handleSubmit} onsuccess={handleSuccess}>
            <lightning-messages></lightning-messages>
            <lightning-input-field value={name} field-name="Name"></lightning-input-field>
            <lightning-input value={name}></lightning-input>
            <lightning-button type="submit" label="Save" class="slds-m-top_medium">
            </lightning-button>
        </lightning-record-edit-form>
    </lightning-card>
</template>

example .js

import {
    LightningElement,
    track
} from 'lwc';

export default class ToDoApp extends LightningElement {
    @track name;

    handleSubmit(event) {
        event.preventDefault();
        const fields = event.detail.fields;
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }

    handleSuccess() {
        // attempt 1
        this.name = '';
        // attempt 2
        this.template.querySelectorAll('lightning-input-field').forEach(each => {
            each.value = '';
        });
    }
}

on success, the lightning-input clears, but the lightning-input-field remains unchanged.

Any ideas?

Answer

This is working as designed. You can modify lightning-input-fields programmatically by changing whatever is specified on their value attribute and it will work…except (here comes the catch)…

Once the user provides any input whatsoever, you cannot programmatically change a lightning-input-field. This is documented in the docs for lightning-input-field:

If a user enters anything in an input field, you can no longer programmatically set the value of the field. The assumption is that there are unsaved changes that should not be overwritten. If you want to be able to overwrite user changes, you can use lightning-input instead.

This special behavior for lightning-input-field conflicts with how properties on all other child components are handled, which makes it very unintuitive. From the LWC docs for Set Properties on Child Components:
“The data binding for property values is one-way. If the property value changes in the owner component, the updated value propagates to the child component.”

Vote for the idea Remove restriction on programmatically setting lightning-input-fields.

Attribution
Source : Link , Question Author : Jake Richter , Answer Author : Peter Knolle

Leave a Comment