gpt4 book ai didi

Angular 2获取元素高度

转载 作者:太空狗 更新时间:2023-10-29 17:34:36 26 4
gpt4 key购买 nike

我这里有一个非常简单的例子

它只是一个带有单个 div 的 Angular 应用

是否可以按 Angular 获取div的高度

我以为我可以用@ViewChild 和 offsetHeight 来做到这一点

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

@Component({
selector: 'my-app',
templateUrl: './src/app.html'
})

export class AppComponent{

@ViewChild('content') elementView: ElementRef;

contentHeight: number;

constructor() {

}

//contentHeight = this.elementView.nativeElement.offsetHeight

}

最佳答案

ViewChild修饰变量elementView只在ngAfterViewInit生命周期钩子(Hook)之后设置:

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

@Component({
selector: 'my-app',
templateUrl: './src/app.html'
})

export class AppComponent implements AfterViewInit {

@ViewChild('content') elementView: ElementRef;

contentHeight: number;

constructor() {

}

ngAfterViewInit() {
this.contentHeight = this.elementView.nativeElement.offsetHeight;
}
}

参见 https://angular.io/api/core/ViewChild#how-to-use了解更多信息。

关于Angular 2获取元素高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49999988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com