我正在尝试执行以下操作:单击一个元素时,我打开另一个元素。我需要计算刚刚打开的那个元素的高度。
我不知道怎么做,因为我没有关于我打开的元素的事件,我将提供一个小的示例代码,以便您了解我想要做的事情。
<div class="parent">
<div class="left">
<div (click)="openRight = !openRight" class="click-element"></div>
</div>
<div *ngIf="openRight" class="right">
</div>
</div>
目标是根据右元素的高度动态设置左元素的高度。右边的元素将具有绝对位置,这就是我需要获得高度的原因。
提前致谢!
答案 0 :(得分:2)
您可以使用DOM
以角度访问#
元素。然后,当您获得点击事件时,您可以访问正确的元素并获得它的高度。
<强> HTML 强>
<div #rightElement class="right">
</div>
<强> TS 强>
import { ElementRef, ViewChild } from '@angular/core';
@ViewChild('rightElement') rightElement: ElementRef;
// get the height
this.rightElement.nativeElement.offsetHeight;
<强> @EDIT 强>
为什么你有一个未定义的孩子是因为你正在使用*ngIf
条件。我认为你正在做类似的事情:
clickEventFunction($event) {
...
this.openRight = true;
...
// Use of the #rightElement
this.rightElement.nativeElement.offsetHeight
...
}
问题是,角度只会在执行openRight
后才会看到您修改了clickEventFunction
,因此#rightElement
不存在而且...... UNDEFINED
!
你能做什么,就是说你做了一个改变的角度,所以它会创建正确的元素然后你可以使用#rightElement
。
示例:
import { ChangeDetectorRef } from 'angular2/core';
constructor(protected chRef: ChangeDetectorRef){
...
}
clickEventFunction($event) {
...
this.openRight = true;
// Tell angular to look at openRight
this.chRef.detectChanges();
...
// Use of the #rightElement
this.rightElement.nativeElement.offsetHeight
...
}
答案 1 :(得分:1)
你可以尝试下面的代码:
<div #mainScreen></div>
组件文件中的
import { ElementRef, ViewChild } from '@angular/core';
export class viewApp{
@ViewChild('mainScreen') elementView: ElementRef;
viewHeight: number;
clickMe(){
this.viewHeight = this.elementView.nativeElement.offsetHeight;
}
}
或
<div *ngFor="let item of items" (click)="clickMe($event.currentTarget)"></div>
clickMe(dom){
let viewHeight=dom.clientHeight;
}
答案 2 :(得分:0)
使用 ES6 ,您可以尝试以下代码:
clickMe(){
let clientHeight = document.getElementById('right').clientHeight;
let offsetHeight = document.getElementById('right').offsetHeight;
let scrollHeight = document.getElementById('right').scrollHeight;
}
clientHeight 包括高度和垂直填充。
offsetHeight 包括高度,垂直填充和垂直边框。
scrollHeight 包含所包含文档的高度(在滚动时大于高度),垂直填充和垂直边框。