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

18

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

例如,如果我正在使用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,但在这种情况下这并不理想。


你没有展示你想要样式化的内容。.sidebar 是指 SidebarComp 本身还是 sidebar.comp.html 内部的某些内容? - Günter Zöchbauer
3个回答

27

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

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

而在伪类中呢? - Alejo Next
@AlejoNext 抱歉,我不知道你的意思。 - Günter Zöchbauer
::before 如何编辑样式?使用 TypeScript 或 JavaScript。 - Alejo Next
我非常确定那不被支持。 - Günter Zöchbauer
@GünterZöchbauer,你在哪里找到这个文档的说明? - NinjaOnSafari
什么部分? - Günter Zöchbauer

4
如果您正在使用百分号(%),请尝试以下方法:
<div class="sidebar-nav"   [style.height.%]="height">

1
在我的情况下,我需要动态切换图片样式的单位为px和%。因此,我使用了[ngStyle]而不是[style.height.px]。我分享给关心此事的人。HTML
<img [src]="imageUrl | safe: 'url'" [ngStyle]="{width: imagewidth, height: imageheight}">

TS

    if (this.properties.imageStyle == 'Stretch') {
      this.imagewidth = this.cols * this.unitWidth + 'px';
      this.imageheight = this.rows * this.unitHeight + 'px';
    }

    if (this.properties.imageStyle == 'Clip') {
      this.imagewidth = 100 + '%';
      this.imageheight = 100 + '%';
    }

https://stackblitz.com/edit/angular-image-clip-stretch


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接