1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Dynamic height calculation incorrect on page load but correct after viewport resize

Discussão em 'Angular' iniciado por Semedmar, Outubro 17, 2024 às 07:13.

  1. Semedmar

    Semedmar Guest

    I have an Angular component that is used with composition, meaning the title of the component changes dynamically based on input. The problem I'm encountering is that when the page loads, the height of the component is calculated as if the title has only one line, making the components look smaller than they should. However, as soon as I resize the window, the height is recalculated correctly.

    I’ve already tried:

    Calling ChangeDetectorRef.detectChanges() in ngAfterContentInit and ngAfterViewChecked. Using requestAnimationFrame to delay the height calculation. Listening to the window’s resize event with @HostListener.

    export class ContentComponent implements AfterContentInit, AfterViewChecked, OnDestroy {

    @ViewChildren('header') headers?: QueryList<ElementRef>;

    private subscriptions = new Subscription();

    constructor(
    private cdRef: ChangeDetectorRef,
    private router: Router,
    ) {
    this.subscriptions.add(
    this.router.events
    .pipe(
    filter((event: Event) => event instanceof NavigationEnd),
    tap(() => this.adjustHeights()),
    )
    .subscribe(),
    );
    }

    ngAfterContentInit(): void {
    this.cdRef.detectChanges();
    this.adjustHeights();
    }

    ngAfterViewChecked(): void {
    if (!this.viewChecked) {
    this.adjustHeights();
    this.viewChecked = true;
    }
    }

    ngOnDestroy(): void {
    this.subscriptions.unsubscribe();
    }

    private adjustHeights(): void {
    const maxHeight = Math.max(...(this.headers?.map((e) => e.nativeElement.scrollHeight) || [0]));
    document.documentElement.style.setProperty('--max-header-height', `${maxHeight}px`);
    }
    @HostListener('window:resize')
    onResize(): void {
    this.adjustHeights();
    }
    }
    `


    html

    <div>
    <div class="header" #header>
    <div class="header-title">
    <h3>{{ title }}</h3>
    </div>
    </div>
    </div>


    What I think might be happening: It seems like the layout isn’t fully settled when I calculate the height on page load, but resizing the viewport forces a reflow that correctly sets the height.

    My question: How can I ensure that the component calculates the correct height on initial load without requiring a viewport resize?

    Any help would be appreciated! Thanks!

    Continue reading...

Compartilhe esta Página