Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 多个样式的角度样式_Angular_Typescript - Fatal编程技术网

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'} : {}"