我这里有一个骗子 - https://plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview
这是一个简单的 Angular 应用程序。
我使用@ViewChild和nativeElement.offsetHeight捕获div的高度
是否可以在组件的样式 block 中使用这个数字。
在我的示例中,我尝试过但将其注释掉。
@Component({
selector: 'my-app',
templateUrl: './src/app.html',
styles: [`
.blockTwo {
background: yellow;
//height: this.contentHeight+px;
height: 200px;
}
`]
})
=
import {Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './src/app.html',
styles: [`
.blockTwo {
background: yellow;
//height: this.contentHeight+px;
height: 200px;
}
`]
})
export class AppComponent implements AfterViewInit{
@ViewChild('content')
elementView: ElementRef;
contentHeight: number;
constructor() {
}
ngAfterViewInit() {
this.contentHeight = this.elementView.nativeElement.offsetHeight;
}
}
最佳答案
这可以使用 ngStyle 实现
在你的 app.html 中将黄色 div 更改为:
<div class="blockTwo" [ngStyle]="style">
</div>
在你的 app.ts 中
style: any;
ngAfterViewInit() {
this.contentHeight = this.elementView.nativeElement.offsetHeight;
this.style = {"height": this.contentHeight+"px"}
}
关于Angular 2,在@Component样式中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003067/