繁体   English   中英

Angular 多个 styles 的 ngStyle

[英]Angular ngStyle for multiple styles

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

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

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

@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无效。

当您使用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 {}
   }
}

试试这个方法

[ngStyle]="isTrue ? {'width': '100%', 'margin-right': '0'} : {}"

您可以在ngStyle枚举多个这样的样式规则:

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

我认为 Angular 已经开始支持单位了。 Angular: 8.2.14工作Angular: 8.2.14

键是样式名称,带有可选的 . 后缀(如'top.px'、'font-style.em')。

现在你可以使用[ngStyle]="{'width.px':200, 'height.px':200}"

如果您像这样定义styleObject ,则this.heightthis.width将是未定义的。 至少,在styleObject中定义ngOnInit ,其中将保证初始化绑定。

对于更动态的感觉,用户可以在组件呈现后更改属性,您可以使用 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; }
}

实际上,您可能可以省略吸气剂。

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

下面的代码显示了如何执行多个 styles:

[ngStyle]="{'left' : calcWidth,'top' : calcHeight}"

如果你需要为不同的样式添加不同的条件,你可以这样做:

 [ngStyle]="{
  'background-color': rank >= 3 ? '#1371FE' : '#E8E8E8',
  'color': rank == 1 ?'white':'#1A1B1C'
}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM