从Angular 2中的变量设置组件样式 [英] Set component style from variable in Angular 2
问题描述
我的目标是使用"styles"属性从组件变量设置样式(在这种情况下为高度和宽度).我认为这里有一个简单的数据绑定方法,但这可能是一厢情愿的想法.
My goal is to set a style (height and width in this case) from a component variable using the "styles" attribute. I would think there is a simple data binding method but that may be wishful thinking...
例如,如果我使用的是html胡子绑定,则它可能看起来像这样:
For example if I were using the html mustache binding it might look like this:
@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,但这在这种情况下并不理想.
Obviously this is all wrong but I've tried some more likely permutations and had no luck finding solutions on the Angular site, Stack Overflow, or Google. I may be reduced to using ngStyle inline but that's not ideal in this case.
推荐答案
您可以设置宿主元素的样式,例如
You can style the host element like
@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'}">
这篇关于从Angular 2中的变量设置组件样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!