我如何获得 .ts文件中的高度

问题描述 投票:2回答:1

我正在使用离子标签来设计我的应用程序,并且在我的一个屏幕上,我想要<div>标签的高度并想要计算下一个视图的高度

任何想法如何在运行时在我的[[.ts文件中获得<div>高度?

代码:

<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>
<div>上方,我的身高动态像[style.height.%]="height",我正在从我的

ts

文件中获取它。但是在此之前,我要前一段的<div>高度。

任何帮助表示赞赏!

提前感谢!

html css typescript ionic2
1个回答
3
投票

在可能的情况下,必须避免直接访问DOM。

一种更好的方法是在视图中使用模板变量:

<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>

然后使用ViewChild在组件代码中获取该元素:

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);
  }

}

请看这个

working stackblitz demo
© www.soinside.com 2019 - 2024. All rights reserved.