Angular ngStyle 用于多个样式

36

我正在开发一个简单的动画库,我的用户可以通过属性绑定来修改我的组件,到目前为止我一直在使用以下方法来应用他们的选择:

<div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div>

但对于未来的扩展,我希望用[ngStyle] =“styleObject”来改变整个混乱的情况,以简化添加更多属性,我正在尝试这样做:

[ngStyle]="{...styleObject, newProperty: newValue}"
@Input() width: number;
@Input() height: number;

public styleObject: Object = {
    'height': this.height,
    'width': this.width
};

但是由于某些原因,<div [ngStyle]="styleObject"></div> 没有考虑上面显示的样式。

请注意,添加 + 'px' 并使用 height.px 并没有解决我的问题。

我看漏了什么?

--

几个测试表明

styleObject = {
    'height': 200 + 'px',
    'background': 'red'
};

这段代码适用于 div,但用 this.height(类型为 number)替换 200 不行。

8个回答

45

尝试这种方法

[ngStyle]="isTrue ? {width: '50px', height: '20px'} : {}"

或者

[ngStyle]="{
  width: '50px', 
  height: '20px'
}"

[ngStyle] 会在页面或应用程序上的任何点击时被多次触发,这会导致性能问题。 - jcdsr
2
我尝试使用Angular 14,并需要添加类似于{'width': '50px','height': '20px'}的引号。 - LacOniC

40

当使用 ngStyle 时,应创建一个返回以下之一的函数:字符串、数组或对象。

如果要返回一个对象,可以按以下方式操作:

在你的模板中:

<div [ngStyle]="styleObject()"></div>

在你的组件中:

export class AppComponent{
 styleObject(): Object {
       if (/** YOUR CONDITION TO SHOW THE STYLES*/  ){
           return {height: this.height,width: this.width}
       }
       return {}
   }
}

@Chris 你很受欢迎 Chris!我很高兴这有帮助到你 :) - Hamed Baatour
1
瓦莱库姆沙拉姆。谢谢Hamed。这对我在Angular 5中很有帮助。 - shaikhspear
2
虽然这个“可行”,但请不要在绑定语句中使用函数。更多信息请参见:https://dzone.com/articles/why-we-shound-not-use-function-inside-angular-temp - Mike Becatti

13

你可以像这样在 ngStyle 中枚举多个样式规则:

<img src="..." [ngStyle]="{'height' : size+'px', 'width' : size+'px'}" />

2
我认为Angular已经开始支持单元。正在使用Angular: 8.2.14进行开发。
关键是一个样式名称,带有可选的.后缀(例如“top.px”,“font-style.em”)。
现在你可以使用[ngStyle] =“{'width.px':200,'height.px':200}”

0

如果您像这样定义styleObjectthis.heightthis.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方法。


用户如何访问这些setter?通过编程实现吗? - Christopher
设值器从模板调用。例如:<your-component [width]="width" />每当宽度变化时,都会调用宽度设值器。 - ppham27

0
如果您需要为不同的样式添加不同的条件,可以按照以下方式进行:
 [ngStyle]="{
  'background-color': rank >= 3 ? '#1371FE' : '#E8E8E8',
  'color': rank == 1 ?'white':'#1A1B1C'
}"

0
以下代码展示了如何实现多种样式:
[ngStyle]="{'left' : calcWidth,'top' : calcHeight}"

0

尝试这种方法 [ngStyle]="{ backgroundColor: 'blue':'transparent', color: 'white'}"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接