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();
}
}