what is the decoration query for in lit-element?
Asked Answered
L

1

5

I can not understand what it exactly does according to the documentation.

This documentation is not detailed enough.

Is there an example?

enter image description here

Lenity answered 26/8, 2019 at 8:50 Comment(0)
B
7

The documentation isn't that deep because what this does isn't that big of a deal, all that this decorator does is create a "shortcut" of sorts for calling querySelector on the element's root (be it this.shadowRoot if you're using shadow dom or this if you're not)

So basically this TS code:

@query('.someClass')
private _someClassElement: Element

is the same as doing this in JS

get _someClassElement() {
  return this.shadowRoot.querySelector('.someClass');
  // or this.querySelector('.someClass') if you're not using shadow dom
}
Broida answered 26/8, 2019 at 9:3 Comment(4)
Hello @Alan I'm trying to use @queryAll for selecting all p tags rendered in parent component but also rendered by childrens component. But i don't know why it looks like it doesn't 'see' the p tags rendered by children and my nodeList is empty. Do you know if something more 'special' needs to be done?Bromal
@Bromal from what you mention, both your parent and children components are using shadow DOM. When using shadow DOM, you cannot query the child component's internal tree from the parent, that's just how the spec works. You could disable shadow DOM on the child component but there's probably a better way of achieving your use case without this kind of query. What are you trying to do?Catheryncatheter
After a failed request, I'm trying to get all p tags content that are not in good format that caused that failed request, and set their content in red to show to the user which p tags are concerned.Bromal
@Bromal in that case it might be easier for you to try to set up a CSS class or something to the relevant p nodes declaratively in a template in the render function rather than imperatively. You could propagate the validation state from the parent component to the children and so on.Catheryncatheter

© 2022 - 2024 — McMap. All rights reserved.