Angular 4如何应用动态样式? [英] Angular 4 how to apply dynamic styles?

查看:121
本文介绍了Angular 4如何应用动态样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为AngFor 4中重复的span元素应用ngFor的动态顶部和左侧值?

Is it possible to apply dynamic top and left values for ngFor repeated span element in Angular 4?

推荐答案

您可以使用:

  1. [style.anything]绑定,例如:<span [style.color]="red"></span>
  2. [ngStyle]绑定允许一次指定多个CSS属性,例如:<span [ngStyle]="{'color': 'red', 'font-weight': condition? 'bold':'300'}"></span>
  3. [className]绑定以动态应用CSS类名称,例如:<span [className]="condition? 'redText': 'blueText'"></span>
  4. [ngClass]绑定,该绑定允许一次指定多个CSS ,就像ngStyle对CSS 属性所做的一样,例如: <span [ngClass]="{'redText': condition1, 'blueText': condition2}"></span>

  1. the [style.anything] binding, eg: <span [style.color]="red"></span>
  2. the [ngStyle]binding that allows specifying multiple CSS properties at once, eg: <span [ngStyle]="{'color': 'red', 'font-weight': condition? 'bold':'300'}"></span>
  3. the [className] binding to apply a CSS class name dynamically, eg: <span [className]="condition? 'redText': 'blueText'"></span>
  4. the [ngClass] binding that allows specifying multiple CSS classes at once, just like ngStyledoes 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(即:它是true1,非空字符串或非空对象;
  • blueText如果i.shouldBeBlue属性的值为true;
  • redText blueText,如果两个属性的评估结果均为true.
  • redText if the attribute i.shouldBeRed evaluates to true (that is: it's true, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆