'Scrolling multiple components

I have 3 components. Let's call them A, B, C.

Component A is a parent component for B and C and it is just container for them.

Component B is unique, it contains a material table with many rows and it have scrollbar.

Component C is can be rendered many times as shown in the picture. Every C component has the same amount of rows as component B.

I need to scroll components B and all of C in the same time. That is, when I scroll component B all of C should scroll too and when I scroll component C, B component and all others C components should scroll too.

// Component B
export class ComponentB {
@ViewChild('scrollBar') scrollBar!: ElementRef;

    ngOnInit(): void {
        this._ScrollService.scroll$.subscribe(scrollTop => {
            this.scrollBar.nativeElement.scrollTop = scrollTop;
        });
    }
    
    updateScroll(): void {
        const scrollBar = this.scrollBar.nativeElement as HTMLElement;
        this._ScrollService.updateScroll(scrollBar.scrollTop);
    }
}

// Component C
export class ComponentC {
@ViewChild('scrollBar') scrollBar!: ElementRef;

    ngOnInit(): void {
        this._ScrollService.scroll$.subscribe(scrollTop => {
            this.scrollBar.nativeElement.scrollTop = scrollTop;
        });
    }
    
    updateScroll(): void {
        const scrollBar = this.scrollBar.nativeElement as HTMLElement;
        this._ScrollService.updateScroll(scrollBar.scrollTop);
    }
}

//ScrollService
export class ContractScrollService {
    private _scroll: Subject<number> = new Subject();
    scroll$ = this._scroll.asObservable();
    updateScroll(scroll: number): void {
        this._scroll.next(scroll);
    }
}
<!-- Component B -->
 <div class="table" #scrollBar (scroll)="updateScroll()">
        <table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
        </table>
 </div>
 
 <!-- Components C -->
 <div class="table" #scrollBar (scroll)="updateScroll()">
        <table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
        </table>
 </div>
 
 <!-- Component A -->
<div class="wrapper">
  <ComponentA></ComponentA>
  <ComponentB *ngFor="let table of tables"></ComponentB>
</div>

I've made it by using the service. The problem is performance. When there's a lot of rows or C components the page get laggy and I don't know how I can optimize it.

Visualization



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source