How to observe @Input in Angular with RxJs

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

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.

Portrait of the author

About me

On a daily basis, I work as a Front-End Developer with a primary focus on JavaScript. I feel most comfortable with Angular and NestJS, but I’m always eager to venture beyond a single tech stack. I effectively leverage AI tools in my workflow, which allows me to quickly onboard into new technologies and write code in other languages or frameworks whenever needed.

After hours, I bring my passion for tech into the physical world. I run my own homelab, where I experiment with server management and build home automation and monitoring powered by Home Assistant.

Leave a comment