JP's programming blog

JP's programming blog

Angular component inputs as RxJS Observable

Did you ever get the impression that Angular's integration with RxJS was somewhat half-baked? One of my gripes is that Angular encourages developers to do everything with RxJS, but then asks us to deal with changes to component inputs by implementing ngOnChange().

So, here's a quick way to add that particular missing piece.

In the class declaration of the component:

inputs$ = new BehaviorSubject<any>({});

(I'll trust your IDE to help you with adding the required RxJS import.)

In the ngOnChange() method:

ngOnChanges(changes: SimpleChanges) {
  const inputs = { ...this.inputs$.value };
  for (const key of Object.keys(changes)) {
    inputs[key] = changes[key].currentValue;
  }
  // console.log('inputs:', inputs);
  this.inputs$.next(inputs);
}

And that's basically it. Unless your component does not have any inputs at all, Angular will call ngOnChanges() before ngOnInit(), passing it the initial values of all the inputs, so you can rely on the observable to contain all of them.

If you want to, you can replace the any type with a class or interface that specifies the type of each of your input fields, which will give you type safety and code completion at the cost of having to specify the input types a second time.

Of course, having the inputs observable is just the beginning - it's downstream that the going will get tough(er). There's plenty of help on RxJS, this blog here caught my eye: Briebug blog.

Cheers!

 
Share this