Angular 多个样式的角度样式
我正在开发一个简单的应用程序,我的用户可以使用属性绑定修改我的组件,到目前为止,我一直在执行以下操作以应用他们的选择:Angular 多个样式的角度样式,angular,typescript,Angular,Typescript,我正在开发一个简单的应用程序,我的用户可以使用属性绑定修改我的组件,到目前为止,我一直在执行以下操作以应用他们的选择: <div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div> 但是由于某种原因,没有考虑上面显示的样式 请注意,添加+'px'并执行height.px并不能解决我的问题 我没有看到什么 -- 一些测试表明 styleObject =
<div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div>
但是由于某种原因,
没有考虑上面显示的样式
请注意,添加+'px'
并执行height.px
并不能解决我的问题
我没有看到什么
--
一些测试表明
styleObject = {
'height': 200 + 'px',
'background': 'red'
};
工作并应用于
div
,但将200
替换为this.height
(类型number
)则不起作用。使用ngStyle
时,应创建一个返回以下内容之一的函数:字符串、数组或对象
如果要返回对象,请执行以下操作:
在模板中:
<div [ngStyle]="styleObject()"></div>
如果像这样定义
styleObject
,this.height
和this.width
将是未定义的。至少,在ngOnInit
中定义styleObject
,保证在其中初始化绑定
为了获得更动态的感觉,用户可以在呈现组件后更改属性,您可以使用getter/setter
它看起来像这样:
export class YourComponent {
styleObject: {[key: string]: string} = {};
@Input()
set width(w: string) {
styleObject = Object.assign({}, styleObject, {width: w});
}
get width() { return styleObject.width; }
@Input()
set height(h: string) {
styleObject = Object.assign({}, styleObject, {height: h});
}
get height() { return styleObject.height; }
}
实际上,您可能可以省略getter。您可以在
ngStyle
中枚举多个类似的样式规则:
<img src="..." [ngStyle]="{'height' : size+'px', 'width' : size+'px'}" />
试试这种方法
[ngStyle]="isTrue ? {'width': '100%', 'margin-right': '0'} : {}"
我想Angular已经开始支持这个单位了。在
角度上工作:8.2.14
键是一个样式名称,带有可选的。后缀(如“top.px”、“font-style.em”)
现在你可以使用
[ngStyle]=“{width.px':200,'height.px':200}”
试试这个方法[ngStyle]=“{backgroundColor:'blue':'transparent',color:'white'}”
@Chris your your your your your welcome Chris!我很高兴这对你有帮助:)WaleykumusSalaam。谢谢你,哈米德。这在Angular 5中对我很有帮助。虽然这“有效”,但请不要在绑定语句中使用函数。更多信息:用户如何访问这些设置器?以编程方式?从模板调用setter。例如:当宽度改变时,将调用宽度设置器。谢谢Omar Hassan
<img src="..." [ngStyle]="{'height' : size+'px', 'width' : size+'px'}" />
[ngStyle]="isTrue ? {'width': '100%', 'margin-right': '0'} : {}"