Lit-element: Make `@query[All]` decorator optionally look in Light DOM

Created on 18 Nov 2019  路  6Comments  路  Source: Polymer/lit-element

https://github.com/Polymer/lit-element/blob/4b0c88c/src/lib/decorators.ts#L155 says "A property decorator that converts a class property into a getter that executes a querySelector on the element's renderRoot."

In my case, @query renderRoot is shadowRoot, but I'd really like to declare some properties for elements expected to be posted into Light DOM by the user.

Is this a feasible idea? Anything I'm missing about how things work?

Most helpful comment

Worth noting, it looks like this is merged in and would come with the next release of lit-element: @queryAssignedNodes(slotName, flatten). Could combine this with a getter to get the slotted input as well.

All 6 comments

AFAIK, it needs to wait until the light DOM has been slotted into SD before it can querySelect.

The MWC implementation does something with a little utility: https://github.com/material-components/material-components-web-components/blob/master/packages/base/src/utils.ts#L24

Would be pretty easy to convert to a decorator, if you really wanted to. We copied this code into our own design library, and it's pretty trivial. Only thing is that it follows the same rules of ::slotted(*), where it will only find the direct child elements, no deeper.

this.querySelector('*') does work instead, but it's a little bit of code smell imo.

I believe this might be something like what you are looking for. I made a decorator similar to query() but for light dom https://github.com/coryrylan/lithium/blob/master/projects/lithium/common/decorators/query-slot.ts If people find this helpful I'd be happy to open a PR.

<my-element>
  <input type="text" />
</my-element>
// this will give you a reference to the input
@querySlot('input') private textInput: HTMLInputElement;

@querySlot sounds perfectly reasonable to me :+1:

Worth noting, it looks like this is merged in and would come with the next release of lit-element: @queryAssignedNodes(slotName, flatten). Could combine this with a getter to get the slotted input as well.

That's right, we're adding @queryAssignedNodes which hopefully covers this use case. Please re-open if this doesn't fit your use case. Thanks.

Was this page helpful?
0 / 5 - 0 ratings