propertyObservable()

Observable creation operator

Creates an observable that emits the value of a property on an component whenever it changes. It can be used to observe changes to a property on a Stencil component, regardless of whether the property is decorated with @Prop(), @State() or not.

While you can use common Stencil way of watching for property changes using @Watch() decorator, this operator allows you to observe property changes in a reactive way, composing it with other observables and operators.

Note

Do note that underlying implementation of this operator uses somewhat hacky way of observing property changes, which may not be future proof. This will change in the future with official release of signal based properties, which will allow to observe property changes in a more robust way.

propertyObservable(cmp, property)

Creates an observable emitting the value of a property on a Stencil component whenever it changes.

function propertyObservable<C extends ComponentInterface, K extends keyof C>(cmp: C, property: K): Observable<C[K]>
function propertyObservable<T = unknown>(cmp: ComponentInterface, property: PropertyKey): Observable<T>;
Arguments:
  • cmp (ComponentInterface) – The Stencil component instance for which to observe the property.

  • property (PropertyKey) – The name of the property to observe.

Returns:

Observable that emits the value of the property whenever it changes.

Return type:

Observable<T>

Hint

Operator can infer the type of property from the component only if the property is declared as public and has a type annotation. Otherwise, you will need to provide the type explicitly or deal with it as any type.

Example

Observe changes to a property on a Stencil component
 1import {
 2    Component,
 3    ComponentInterface,
 4    h,
 5} from '@stencil/core';
 6import { propertyObservable } from '@runopenode/rxjs-stencil';
 7import { Observable } from 'rxjs';
 8
 9@Component({
10    tag: 'my-cmp',
11    shadow: true,
12})
13class MyCmp implements ComponentInterface {
14
15    public myProp: string;
16
17    public constructor() {
18         propertyObservable<string>(this, 'myProp')
19             .subscribe((value: string): void => {
20                 // Handle property change
21             });
22    }
23
24    public render(): any {
25        // Render component template
26    }
27}