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.

1
@Component({
2
/* ... */
3
})
4
export class ExampleComponent implements OnDestroy {
5
@Input() set userId(userId: number) {
6
this.userId$.next(userId);
7
}
8
9
private userService = inject(UserService);
10
private userId$ = new ReplaySubject<number>(1);
11
userDetails$ = this.userId$.pipe(
12
switchMap((userId) => this.userService.getUserDetails(userId)),
13
shareReplay(1),
14
);
15
16
ngOnDestroy() {
17
this.userId$.complete();
18
}
19
}

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