简体   繁体   中英

Focusing element via binding doesn't always work

Given following view model:

export class ExpandingInput {  
    // ctor
    constructor() {
        this.expanded = false;
    }

    // actions
    toggle() {
        this.expanded = !this.expanded;
    }
}

and template:

<template>

    <div class="expanded-input wrapper">
        <input focus.trigger="toggle()" />

        <textarea if.bind="expanded"
                  focus.bind="expanded"
                  blur.trigger="toggle()"
                  rows="4">
        </textarea>
    </div>

</template>

The behavior is that when I first click/tab into/otherwise focus the input element, the textarea element shows up and is focused. Then I click somewhere else, so that the textarea looses focus. Now when I again click on the input, the textarea shows up but is not focused (input element is).

Expected/desired behavior would be for the html elements to always behave consistently, not only on the first time :).

Two notes: if I remove the if.bind expression , it works. I went around this problem by not using if.bind and instead binding css classes to hide/show element like that class="${expanded ? 'show' : 'hide'}" but I don't think the former should work as it is now.

As the textarea's focus state actively alters the rendering (detaches it from the DOM), its focus / blur event listeners are detached as well, so they only work the first time.

From the docs :

[…] if removes the element entirely from the DOM, and show toggles the aurelia-hide CSS class which controls the element's visibility.

To avoid this without having to worry about (re-)binding listeners, use the show conditional instead of if .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM