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

标签 html css angular

我的目标是使用“样式”属性从组件变量设置样式(在本例中为高度和宽度)。我认为有一种简单的数据绑定(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/

相关文章:

javascript - 第一次单击后 JQuery 函数停止工作

html - Angular 标与导航菜单冲突

angular - 如何在 Angular2 中追加/更新查询参数

html - 位置 : Fixed Div Covers Images

javascript - jQuery 循环遍历相同的类名

php - Wordpress 响应式主题, Logo 在浏览器中显示不同

css - Chrome 移动设备屏幕模拟器

css - 页面速度字体链接谷歌字体

javascript - 以正确的方式禁用 Angular 5 输入字段

javascript - ionic 2 : Google Map Custom Controls Not Working