在Angular 2中动态更新css

新手上路,请多包涵

假设我有一个 Angular2 组件

//home.component.ts

import { Component } from 'angular2/core';

@Component({
    selector: "home",
    templateUrl: "app/components/templates/home.component.html",
    styleUrls: ["app/components/styles/home.component.css"]
})
export class HomeComponent {
    public width: Number;
    public height: Number;
}

此组件的模板 html 文件

//home.component.html

<div class="home-component">Some stuff in this div</div>

最后是这个组件的 css 文件

//home.component.css

.home-component{
    background-color: red;
    width: 50px;
    height: 50px;
}

如您所见,该类中有 2 个属性, widthheight 。我希望宽度和高度的 css 样式与宽度和高度属性的值相匹配,并且当属性更新时,div 的宽度和高度也会更新。实现此目的的正确方法是什么?

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

阅读 340
2 个回答

尝试这个

 <div class="home-component"
 [style.width.px]="width"
 [style.height.px]="height">Some stuff in this div</div>

[更新]:设置百分比使用

[style.height.%]="height">Some stuff in this div</div>

原文由 Gaurav Mukherjee 发布,翻译遵循 CC BY-SA 3.0 许可协议

要在 @Gaurav 的回答中使用 % 而不是 px 或 em ,它只是

<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题