要创建一个单个类绑定,可以输入以下内容:[class.sale]="onSale"

 

当绑定的表达式 onSale 的值为真时,Angular会添加这个类,当表达式的值为假时,它会移除这个类(除了 undefined 的情况)

 

绑定多个 CSS 类

 

[class]="classExpression"

 

表达式可以是以下之一:

  1. 由空格分隔的类名字符串

  2. 一个以类名为键,真值或假值表达式为值的对象

  3. 一个类名数组

使用对象格式时,只有当与其关联的值为真时,Angular 才会添加类

如果对同一个类名有多个绑定,Angular 会使用样式优先级来确定使用哪个绑定

 

BINDING TYPESYNTAXINPUT TYPEEXAMPLE INPUT VALUES
Single class binding[class.sale]="onSale"boolean | undefined | nulltrue, false
Multi-class binding[class]="classExpression"string"my-class-1 my-class-2 my-class-3"
Multi-class binding[class]="classExpression"Record<string, boolean | undefined | null>{foo: true, bar: false}
Multi-class binding[class]="classExpression"Array<string>['foo', 'bar']


绑定到单一样式

 

要创建一个单个样式绑定,使用前缀 style,后跟一个点和 CSS 样式的名称

例如,要设置宽度样式,可以输入以下内容:[style.width]="width"

Angular 将该属性设置为绑定表达式的值,通常是一个字符串。可选地,您可以添加单位扩展,如 em 或 %,这需要一个数字类型

 

<nav [style.background-color]="expression"></nav>
<nav [style.backgroundColor]="expression"></nav>

 

 

绑定多种样式

 

要切换多个样式,请绑定到 [style] 属性,例如 [style]="styleExpression"。styleExpression 可以是以下之一:

  • 一个样式字符串列表,例如 "width: 100px; height: 100px; background-color: cornflowerblue;
  • 一个以样式名称为键,样式值为值的对象,例如 {width: '100px', height: '100px', backgroundColor: 'cornflowerblue'}


请注意,不支持将数组绑定到 [style]
当将 [style] 绑定到对象表达式时,必须改变对象的身份才能使 Angular 更新类列表。如果不改变对象身份,更新属性将没有效果

 

BINDING TYPESYNTAXINPUT TYPEEXAMPLE INPUT VALUES
Single style binding[style.width]="width"string | undefined | null"100px"
Single style binding with units[style.width.px]="width"number | undefined | null100
Multi-style binding[style]="styleExpression"string"width: 100px; height: 100px"
Multi-style binding[style]="styleExpression"Record<string, string | undefined | null>{width: '100px', height: '100px'}