I have an Angular 10 component that displays a list of film titles, the list has a vertical scroll bar. One of these will be the currently selected film and be displayed highlighted in bold etc. The film list and the selected film are updated via observables as so:
<div
class="overflow-hidden text-nowrap"
[ngClass]="{'shadow-sm font-weight-bolder': isSelected(film.id)}"
*ngFor="let film of films"
(click)="onClick(film)">
{{film.title}}
</div>
and
public ngOnInit(): void {
this.subs.push(this.filmService.observe().subscribe(films => {
this.films = films;
this.changeRef.detectChanges();
}));
this.subs.push(this.activeFilmService.observe().subscribe(film => {
this.activeFilm = film;
this.changeRef.detectChanges();
}));
}
public isSelected(id: number): boolean {
return this.activeFilm && id === this.activeFilm.id;
}
Unfortunately the active film is often not visible without the user manually scrolling down to find it. I want to bring the active film into view every time either the list or the active film changes. I know how I might do this using @ViewChild to find the div and call scrollIntoView() to make it visible. My question is where should I add this code?
Presumably I can't just add the scrollIntoView code to the end of the subscription. I assume I have to wait for Angular to re-render all the elements before trying to change the scroll position. How would I safely do this?