How to observe @Input in Angular with RxJs

Angular does not provide something like AsyncInput, but you can work around with ReplaySubject

July 19, 2022 angularangular-17

Observable inputs

In Angular, you can use RxJS to observe changes in an @Input property. To observe changes in this input property using RxJS, you can use push next value to ReplaySubject when a new value arrived.

@Component({
  /* ... */
})
export class ExampleComponent implements OnDestroy {
  @Input() set userId(userId: number) {
    this.userId$.next(userId);
  }

  private userService = inject(UserService);
  private userId$ = new ReplaySubject<number>(1);
  userDetails$ = this.userId$.pipe(
    switchMap((userId) => this.userService.getUserDetails(userId)),
    shareReplay(1),
  );

  ngOnDestroy() {
    this.userId$.complete();
  }
}

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment