polymerpolymer-3.xdom-repeat

How to access elements within dom-repeat in Polymer 3.0?


I have the following piece of code:

<dom-repeat id="template" items="{{chats}}">
    <template>
      <template is="dom-if" if="[[item.opened]]">
        <section id$="msg-[[index]]"></section>
      </template>
    </template>
</dom-repeat>

How do can I access section with id=msg-3 and set scrollTop to 999 upon being rendered?

I know that in polymer 1 the best practice was to bind to on attached and wait on a dom-repeat event with a debouncer this no longer works in polymer 3, however.


Solution

  • If you know the index number you can access the element with ;

    let el = this.shadowRoot.querySelector('#msg-'+<index>);
    

    Remember, if item not rendered due to your filter with dom-if, you can not acces this element.

    EDIT

    In order to show on top of the selected item;

    let screenPosition = el.getBoundingClientRect();
    window.scrollTo(screenPosition);
    

    Demo