Angular 4如何应用动态样式? [英] Angular 4 how to apply dynamic styles?
问题描述
是否可以为AngFor 4中重复的span元素应用ngFor的动态顶部和左侧值?
Is it possible to apply dynamic top and left values for ngFor repeated span element in Angular 4?
推荐答案
您可以使用:
-
[style.anything]
绑定,例如:<span [style.color]="red"></span>
-
[ngStyle]
绑定允许一次指定多个CSS属性,例如:<span [ngStyle]="{'color': 'red', 'font-weight': condition? 'bold':'300'}"></span>
-
[className]
绑定以动态应用CSS类名称,例如:<span [className]="condition? 'redText': 'blueText'"></span>
-
[ngClass]
绑定,该绑定允许一次指定多个CSS 类 ,就像ngStyle
对CSS 属性所做的一样,例如:<span [ngClass]="{'redText': condition1, 'blueText': condition2}"></span>
- the
[style.anything]
binding, eg:<span [style.color]="red"></span>
- the
[ngStyle]
binding that allows specifying multiple CSS properties at once, eg:<span [ngStyle]="{'color': 'red', 'font-weight': condition? 'bold':'300'}"></span>
- the
[className]
binding to apply a CSS class name dynamically, eg:<span [className]="condition? 'redText': 'blueText'"></span>
the
[ngClass]
binding that allows specifying multiple CSS classes at once, just likengStyle
does for CSS properties, eg:<span [ngClass]="{'redText': condition1, 'blueText': condition2}"></span>
[ngClass]
接收一个对象作为其输入,并且仅当相应值求值为true时,才应用该对象的每个键.
[ngClass]
receives an object as its input, and applies each one of that object's keys only if the respective value evaluates to true.
例如,如果要遍历数组items_array
:
For instance, if you're iterating over the array items_array
:
<span *ngFor="let i of items_array"
[ngClass]="{'redText': i.shouldBeRed, 'blueText': i.shouldBeBlue}">
The span text
</span>
<span *ngFor="let i of items_array"
[ngClass]="{'redText': i.shouldBeRed, 'blueText': i.shouldBeBlue}">
The span text
</span>
每个元素(i
)的CSS类将是:
the CSS class of each element (i
) will be:
-
redText
,如果属性i.shouldBeRed
的计算结果为true(即:它是true
,1
,非空字符串或非空对象; -
blueText
如果i.shouldBeBlue属性的值为true; -
redText blueText
,如果两个属性的评估结果均为true.
redText
if the attributei.shouldBeRed
evaluates to true (that is: it'strue
,1
, a non-empty string, or a non-null object;blueText
if the attribute i.shouldBeBlue evaluates to true;redText blueText
if both attributes evaluate to true.
在您的情况下,我认为[ngStyle]
是合适的:
In your case, I guess that [ngStyle]
would be appropriate:
<span *ngFor="let i of items_array"
[ngStyle]="{'top': expression1, 'left': expression2}">
The span content
</span>
<span *ngFor="let i of items_array"
[ngStyle]="{'top': expression1, 'left': expression2}">
The span content
</span>
这篇关于Angular 4如何应用动态样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!