Search code examples
htmlcsstypescriptionic2

How Can I Get <div> height in my .ts file


I am using ionic tags to design my application and at one of my screen I want <div> tag's height and want to calculate next view height

Any Idea how to get <div> height at runtime in my .ts file?

Code:

 <div *ngIf="affectedItemsViewShowFlag" class="affected-items-list-style" [style.height.%]="height">
      <ion-list *ngSwitchCase="'affected item'" class="list-style">
        <ion-grid no-padding>
          <ion-row *ngFor="let keyValue of affectedItemJsonKeyValues">
            <ion-col col-6>
              <ion-item>
                <ion-label class="key-font-style">{{ keyValue }}</ion-label>
              </ion-item>
            </ion-col>
            <ion-col col-6>
              <ion-item class="column-remove-padding">
                <ion-label class="value-font-style">{{ faCaseDetails.affected_item[keyValue] }}</ion-label>
              </ion-item>
            </ion-col>
          </ion-row>
        </ion-grid>
      </ion-list>
    </div>

in above <div> my height dynamic like [style.height.%]="height" and I am fetching this from my ts file.

But before that, I want <div> height of the previous one segment.

any help appreciated!

Thanks in advance!


Solution

  • Even though var height = document.getElementById('myDiv').offsetHeight; would work, that's not the best way to access to the DOM in an Angular application.

    Direct access to the DOM must be avoided when possible.

    A better way to do that would be by using a template variable in the view:

    <ion-header>
    ...
    </ion-header>
    
    <ion-content padding>    
      <div #target style="background-color:yellow; height:100px;"></div>    
      <p>The height of the div is: {{ result }}px</p>
    </ion-content>
    

    And then using ViewChild to get that element in the component code:

    import { Component, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
    
      @ViewChild('target') targetElement: any;    
      result: string;
    
      constructor() {}
    
      ngOnInit() {
        // Get the height of the element
        const height = this.targetElement.nativeElement.offsetHeight;
    
        // Here you can use the height!
        this.result = height;
        console.log(height);
      }
    
    }
    

    Please take a look at this working stackblitz demo.