Angular viewChild native scrollable CSS window layout quirks

Discussão em 'Angular' iniciado por Jan Nielsen, Janeiro 7, 2025.

  1. Jan Nielsen

    Jan Nielsen Guest

    Embedded in a large Angular 19 application, I have a component with a scroll-able window where the content outside the window is hidden, i.e., the window content extends beyond the top and bottom of the fixed window and the content can be centered with a button press.

    Initial centering of the content is done with an effect in the constructor:

    element = viewChild.required<ElementRef>('my-container');

    #scrollTo = computed(() => {
    const nativeElement = this.element().nativeElement;
    const scrollHeight: number = nativeElement.scrollHeight;
    const offsetHeight: number = nativeElement.offsetHeight;

    return 4 + (scrollHeight - offsetHeight) / 2;
    });

    constructor() {
    effect(() => {
    this.element().nativeElement.scrollTo(0, this.#scrollTo());
    });
    }



    Most of the time scrollHeight is 700px and offsetHeight is 300px and things work properly; however, about one in ten or fifteen refreshes (in Chrome) the scrollHeight and offsetHeight are the same, in this case 38px which cause the centering to fail.

    I'm guessing this is race-condition between the Chrome's layout calculation and the scrollTo signal calculation? Any ideas how to fix this calculation and/or behavior, without introducing a delay in the component constructor?

    Continue reading...

Compartilhe esta Página