@consumeContext
To consume a context in a component, you can use the @consumeContext
decorator. This decorator takes an object with the following properties:
context
: The context object that you want to consume.
import { myContext } from './my-element-provider'
@customElement("my-consumer")
export class MyElement extends RadiantElement {
@consumeContext(myContext)
consumer!: ContextProvider<typeof myContext>;
Once you have a context consumer, you can access the context value using the consumer
property and the following properties:
-
getContext()
: Returns the context value. -
setContext(value: Partial
: Sets the context value.)
Please note that is possible to consume multiple contexts in the same component.
If you need more fine-grained control over the context, you can use the @contextSelector
decorator, you can read more about it here.
If for any reason you don't want to use the @consumeContext
decorator, you can simply send a custom event to the provider element with the context value.
import { myContext } from './my-element-provider';
import { ContextRequestEvent } from '@ecopages/radiant';
@customElement("my-consumer")
export class MyElement extends RadiantElement {
context!: ContextProvider<typeof myContext>;
connectedCallback() {
super.connectedCallback();
this.dispatchEvent(new ContextRequestEvent(myContext, (context) => this.context = context));
}
}