I am using Lit Custom Elements:
I am using component A in my component B and want to access the property letters of B (from child to parent element). How do I do that?
// Component A
@customElement('a-component')
class AComponent extends LitElement {
@property() public letters = ['a', 'b', 'c' ]
//.....
// Component B
// ...
<a-component id="a"></add-photo-component>
//....
I am using component A in my component B and want to access the property letters of B (from child to parent element). How do I do that?
Simple answer: You don't. At least not in that direction. If component A needs to know letters, have component B pass it into A via properties or attributes.
Your thought concept is problematic because it violates the basic idea of components. Components are meant to encapsulate what they do; a child component is never meant to access components outside of its own scope (including any parent components). A component should not know anything about its context (that is, their parent or any other ancestors, except those always present (e.g. document.body
, and even those should only be accessed if your component is connected, which you can always check via the boolean built-in-property this.isConnected
)). This concept is called de-coupling and is widely considered the architectural go-to-standard in a componentized world.
Otherwise you are sort of hard-wiring your component to that context, making it either useless or throw errors when you want to re-use that component in other contexts.
If there is anything that comes from outside and the component needs to know about it (e.g. data), then pass that to the child component via properties or attributes.
If interaction with the child component cannot be handled by the component itself, inform the outside world about it via custom events. In that case it would be any of the ancestor components' job to pick up on this (it would then have a listener for that event), and do something with it, and if the result of that is supposed to affect that child component, then pass it into that component, again via properties or attributes, or by e.g. calling a callback that might have been part of the custom event data the child component had issued.