Mobina Khalilzade
Mobina Khalilzade

Reputation: 57

How can I get the height of an element while it's collapsed in DOM in Angular/Typescript

I've tried ngOnInit() but didn't succeed. Accordion doesn't work too. Here is my html :

<div [hidden]="advancedFiltersAreShown" #searchDiv></div>
<button *ngIf="advancedFiltersAreShown" (click)="advancedFiltersAreShown=!advancedFiltersAreShown; minHeightOfTable();"></button>

.ts code:

 @ViewChild('searchDiv', { static: true }) elementView: ElementRef;
 primeTableHeight = '';
 advancedFiltersAreShown = true;

 minHeightOfTable(): string {
        const heightOfPage = window.innerHeight;
        const heightOfSearchView = this.elementView.nativeElement.offsetHeight;
        var newHeight = heightOfPage - heightOfSearchView;
        this.primeTableHeight = newHeight + 'px';
        return this.primeTableHeight;

    }

Upvotes: 1

Views: 1267

Answers (1)

Mehdi Daustany
Mehdi Daustany

Reputation: 1226

As I get from your code, you have a button which collapse your div element, so you want to resize your other element in your page after collapsing/opening your div (Custom Accordion). Lets imagine you have two DIV and a button to collapse/open first DIV.

<div #container>
    <button *ngIf="advancedFiltersAreShown" (click)="advancedFiltersAreShown=!advancedFiltersAreShown; calculateElementSize();"></button>
    <div #searchDiv>
    </div>
    <div #otherElement>
    </div>
</div>

You have to implement an event handler on your button to resize your second div according to your clients resolution.

So, first of all you have to declare a function calculateElementSize() and pass these steps:

  • Get height of main #container DIV or body that your elements rendered in it.
  • Get height of first (Search) floating DIV.
  • Deduce #searchDIV height's from #container height's
  • Set the result of subtraction to #otherElement height's
  • Set the calculateElementSize() to your button event and windows resize event.

Lets do it:

import { Component, ViewChild, HostListener, AfterViewInit } from '@angular/core';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage implements AfterViewInit {

  @ViewChild('container', { static: true }) containerElement: any;
  @ViewChild('searchDIV', { static: true }) searchElement: any;
  @ViewChild('otherElement', { static: true }) otherElement: any;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
      this.calculateElementSize();
  }

  advancedFiltersAreShown = true;

  constructor() {}

  ngAfterViewInit() {
    this.calculateElementSize();
  }

  calculateElementSize() {
    const containerHeight = this.containerElement.nativeElement.offsetHeight;
    const searchHeight = this.searchElement.nativeElement.offsetHeight;

    this.otherElement.nativeElement.offsetHeight = containerHeight - searchHeight;
  }

}

Upvotes: 1

Related Questions