假设我有一个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个属性, width
和 height
. 我希望宽度和高度的css样式与width和height属性的值匹配,当属性更新时,div更新的宽度和高度 . 完成此任务的正确方法是什么?
10 回答
试试这个
[更新]:设置%使用
要使用%而不是px或em与@Gaurav的答案,它只是
这应该这样做:
您还可以使用hostbinding:
现在,当您从HomeComponent中更改width或height属性时,这应该会影响样式属性 .
Check working Demo here
您可以通过将动态值附加到div的内联[style.width]和[style.hiegh]属性来动态更改div的样式(宽度和高度) .
在您的情况下,您可以将HomeComponent类的width和height属性与div的内联样式width和height属性绑定,如下所示... As directed by Sasxa
有关工作演示,请查看此plunker(http://plnkr.co/edit/cUbbo2?p=preview)
以上所有答案都很棒 . 但是,如果你试图找到一个不会改变下面的html文件的解决方案是有帮助的
您可以从
import {Renderer} from '@angular/core';
导入渲染器接受的答案并不正确 .
对于分组样式,也可以使用ngStyle指令 .
官方文档是here
如果要使用变量动态设置宽度而不是使用[]括号{{}}:
我喜欢上面的 WenhaoWuI 的想法,但我需要在 PrimeNG tree component 中用 class
.ui-tree
识别div来动态设置高度 . 我能找到的所有答案都需要命名div(即#treediv)才能使用@ViewChild()
,@ViewChildren()
,@ContentChild()
,@ContentChilden()
等 . 这对第三方组件来说很麻烦 .我终于找到了一个来自Günter Zöchbauer的片段:
这很容易: