我的目标是使用“样式”属性从组件变量设置样式(在本例中为高度和宽度)。我认为有一种简单的数据绑定(bind)方法,但这可能是一厢情愿的想法......
例如,如果我使用 html mustache 绑定(bind),它可能看起来像这样:
@Component({
selector: '[sidebar]',
templateUrl: 'app/Nav/sidebar.comp.html',
styles: [`
.sidebar-nav {
overflow: scroll;
height: {{ height }};
}
.sidebar {
height: {{ 0.9 * height }};
width: {{ 0.21 * width }};
}
`]
})
export class SidebarComp {
width: number;
height: number;
constructor() {
this.height = window.innerHeight;
this.width = window.innerWidth;
}
}
显然这都是错误的,但我已经尝试了一些更可能的排列,但没有在 Angular 网站、Stack Overflow 或 Google 上找到解决方案。我可能会减少使用 ngStyle 内联,但在这种情况下这并不理想。
最佳答案
您可以像这样设置宿主元素的样式
@Component({
selector: '[sidebar]',
templateUrl: 'app/Nav/sidebar.comp.html',
host: {
'[style.height.px]':'0.9 * height',
'[style.width.px]':'0.21 * width'
}
})
export class SidebarComp {
width: number;
height: number;
constructor() {
this.height = window.innerHeight;
this.width = window.innerWidth;
}
}
和内容(app/Nav/sidebar.comp.html
)如
<div class="sidebar-nav" [style.overflow]="'scroll'" [style.height.px]="height">
或
<div class="sidebar-nav" [ngStyle]="{overflow: 'scroll', height: height + 'px'}">
关于html - 从 Angular 2 中的变量设置组件样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130705/