4

I have a lightning component with lightning-input type checkbox and formatted-text.

By default formatted-text shown,

  1. If double click the formatted-text, it is hide and lightning-input shown.
  2. If blur the lightning-input, it is hide and formatted-text shown.

The problem was, if checkbox value changed onblur called, so each time checkbox value changed, the formatted-text shown. How to fix this?

I need to hide the checkbox it is blur only, don't hide it value change.

playground link

js file

export default class App extends LightningElement {
    isRendered = false;
    mode = 'VIEW';
    value = true;

    get isEditMode() {
        return this.mode === 'EDIT';
    }

    get isViewMode() {
        return this.mode === 'VIEW';
    }

    handleOnChange(event) {
        console.log('on_change');
        this.value = event.target.checked;
    }

    handleOnBlur(event) {
        console.log('on_blur');
        this.mode = 'VIEW';
    }

    handleOnDblClick() {
        this.mode = 'EDIT';
    }
}

html file

<template>
    <template if:true={isViewMode}>
        <div ondblclick={handleOnDblClick}>{value}</div>
    </template>
    <template if:true={isEditMode}>
        <lightning-input type="checkbox"
            label=" "
            checked={value}
            onchange={handleOnChange}
            onblur={handleOnBlur}>
        </lightning-input>
    </template>
</template>
2

You can use mouseenter and mouseleave events to enable and disable blur logically. Have a boolean to set to true and false depending on where the mouse is.

html:

<template>
    <template if:true={isViewMode}>
        <div ondblclick={handleOnDblClick}>{value}</div>
    </template>
    <template if:true={isEditMode}>
        <div onmouseenter={handleMouseEnter} onmouseleave={handleMouseLeave}>
            <lightning-input type="checkbox"
                            label=" "
                            checked={value}
                            onchange={handleOnChange}
                            onblur={handleOnBlur}>
            </lightning-input>
        </div>
    </template>
</template>

JS:

handleMouseEnter() {
    console.log('handleMouseEnter');
    this._processBlur = false;
}

handleMouseLeave() {
    console.log('handleMouseEnter');
    this._processBlur = true;
}

handleOnBlur(event) {
    if(this._processBlur) {
        console.log('on_blur');
        this.mode = 'VIEW';
    }
}

Note:

Instead of double click and blur events, you can probably think about achieving same thing via mouseenter and mouseleave. On mouseenter, show editable mode and on mouseleave, show readable mode.

playground link

1
  • It is working fine me, Thank you. Jun 12 '20 at 10:38

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.