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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38130705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:29:46  来源:igfitidea点击:

Set component style from variable in Angular 2

htmlcssangular

提问by Methodician

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...

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

For example if I were using the html mustache binding it might look like this:

例如,如果我使用 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;
    }
}

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.

显然这都是错误的,但我尝试了一些更可能的排列,但没有在 Angular 站点、Stack Overflow 或 Google 上找到解决方案。我可能会减少使用 ngStyle 内联,但这在这种情况下并不理想。

回答by Günter Z?chbauer

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;
    }
}

and the content (app/Nav/sidebar.comp.html) like

和内容 ( app/Nav/sidebar.comp.html) 喜欢

<div class="sidebar-nav" [style.overflow]="'scroll'" [style.height.px]="height">

or

或者

<div class="sidebar-nav" [ngStyle]="{overflow: 'scroll', height: height + 'px'}">

回答by MedElmaachi

If you are using percent (%) try this :

如果您使用百分比 (%) 试试这个:

<div class="sidebar-nav"   [style.height.%]="height">