多种样式的Angular ngStyle

Chr*_*her 8 typescript angular

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

<div [style.background]="color" [style.width.px]="width" [style.height.px]="height"></div>
Run Code Online (Sandbox Code Playgroud)

但是对于未来的添加,我希望改变这整个混乱[ngStyle]="styleObject"以简化添加更多属性,我试图实现这样这样:

@Input() width: number;
@Input() height: number;

public styleObject: Object = {
    'height': this.height,
    'width': this.width
};
Run Code Online (Sandbox Code Playgroud)

但由于某种原因<div [ngStyle]="styleObject"></div>没有考虑到上面显示的风格.

请注意,添加+ 'px'和执行height.px操作并不能解决我的问题.

我没看到什么?

-

一些测试表明了这一点

styleObject = {
    'height': 200 + 'px',
    'background': 'red'
};
Run Code Online (Sandbox Code Playgroud)

工作并应用于div,但200this.height(类型number)替换不.

Ale*_*pov 24

试试这个方法

[ngStyle]="isTrue ? {'width': '100%', 'margin-right': '0'} : {}"
Run Code Online (Sandbox Code Playgroud)

  • 我尝试使用 Angular 14 并需要添加 ' like {'width': '50px', 'height': '20px'} (2认同)

Ham*_*our 10

Assalamualaikum,

在使用时,ngStyle您应该创建一个返回以下内容之一的函数:字符串,数组或对象.

如果要返回Object,请执行以下操作:

在您的模板中:

<div [ngStyle]="styleObject()"></div>
Run Code Online (Sandbox Code Playgroud)

在您的组件中:

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

  • 尽管这“有效”,但请不要在绑定语句中使用函数。更多信息在这里:https://dzone.com/articles/why-we-shound-not-use-function-inside-angular-temp (2认同)

ygl*_*odt 8

你可以在里面枚举多个这样的样式规则ngStyle

<img src="..." [ngStyle]="{'height' : size+'px', 'width' : size+'px'}" />
Run Code Online (Sandbox Code Playgroud)