Cod*_*ger 2 html css typescript ionic2
我正在使用离子标签来设计我的应用程序,并且在我想要的屏幕之一上<div>标签的高度并想要计算下一个视图高度
知道如何<div>在运行时在我的.ts文件中获取高度吗?
代码:
<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>
Run Code Online (Sandbox Code Playgroud)
在高于<div>我的高度的动态中[style.height.%]="height",我从我的ts文件中获取它。
但在此之前,我想要<div>前一段的高度。
任何帮助表示赞赏!
提前致谢!
尽管var height = document.getElementById('myDiv').offsetHeight;可行,但这并不是在 Angular 应用程序中访问 DOM 的最佳方式。
必须尽可能避免直接访问 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>
Run Code Online (Sandbox Code Playgroud)
然后使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
请看一下这个工作 stackblitz 演示。