从 Angular 2 中的变量设置组件样式

新手上路,请多包涵

我的目标是使用“样式”属性从组件变量设置样式(在本例中为高度和宽度)。我认为有一种简单的数据绑定方法,但这可能是一厢情愿的想法……

例如,如果我使用 html mustache 绑定,它可能看起来像这样:

 @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 inline 但这在这种情况下并不理想。

原文由 Methodician 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 241
1 个回答

您可以像这样设置主机元素的样式

@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'}">

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题