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

A JavaScript specialist with many years of industry experience whose heart beats for Angular. A follower of the "Keep it simple, stupid" principle and a fan of clean code and good architecture. Fearless in the face of the toughest challenges, I always look for simple and effective solutions. As a pragmatist and an enthusiast of new technologies, I passionately follow the trends in the JavaScript world. After hours — a sailor who loves discovering new places and spending time on trips. My favorite motto? "Talk is cheap. Show me the code."

Leave a comment