angular - Angular 2,在@Component 样式中使用变量
问题描述
我在这里有一个 plunker - https://plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview
它是一个简单的角度应用程序。
我正在使用 @ViewChild 和 nativeElement.offsetHeight 捕获 div 的高度
是否可以在组件的样式块中使用此数字。
在我的示例中,我尝试过但将其注释掉。
@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"}
}
推荐阅读
- symfony - 将 SF 从 2.8 升级到 3.xx
- asp.net-core - 哪些 ASPNetCore 包与 netcoreapp2.1 兼容?
- javascript - 如何根据我使用 selenium python 的 HTML 数据获取 HTML 索引?
- android - 如何等待 firebase 查询完成?
- angular - '$ 未定义' | Angular 6 中的服务器端渲染
- python - 邮件的 ReceivedTime 未在 python 中显示
- ios - 如何在适用于 iOS 的 React 应用程序上隐藏滚动条
- gnuplot - 系统时间和 Gnuplot
- cordova - 如何在 ionic 3 中修复错误运行“ionic cordova build ios --prod”?
- openvswitch - “ovs-dpctl show”命令是什么意思?