简谈 Angular 动态绑定样式的几种方法
动态绑定样式的本质是操作元素的 class 列表和内联样式。因为 class 和 style 都是 attribute,所以我们可以用 Attribute 绑定处理它们:只需要通过表达式计算出字符串结果即可。同理我们也可以用 Property 绑定处理。另外,Angular 还提供了专门的 class Attribute 绑定和 style Attribute 绑定。内置属性型指令 NgClass 和 NgStyle 也是用来动态绑定样式的。
一、绑定 HTML Class
(一)Attribute 绑定
语法 | 输入类型 |
---|---|
[attr.class]="classExp" | string |
该方法的优先级最高,表达式结果是最终的 class 属性值。
(二)Property 绑定
语法 | 输入类型 |
---|---|
[className]="classExp" | string |
该方法的优先级比 Attribute 绑定低,表达式结果是最终的 class 属性值。
(三)class Attribute 绑定
绑定类型 | 语法 | 输入类型 |
---|---|---|
单 class 绑定 | [class.key]="classExp" | boolean | undefined | null |
多 class 绑定 | [class]="classExp" | string| Array<string> | |
该方法会更新 class 属性值,更新逻辑取决于结果的类型。
单 class 绑定:
- 当绑定的值为真的时候添加,为假则移除。
多 class 绑定:
- string - 会把列在字符串中的 classes(空格分隔)添加进来,
- Array - 会把数组中的各个元素作为 classes 添加进来,
- Object - 每个 key 都是要处理的 class,当 value 的值为真的时候添加,为假则移除。
(四)内置属性型指令 NgClass 绑定
语法 | 输入类型 |
---|---|
[ngClass]="classExp" | string | Array<string> | Set<string> | |
该方法类似于上面的多 class 绑定,但是功能更加强大,比如:
- 支持输入 Set 类型,
- 输入 Object 类型时支持 key 中带空格(表示多个 class)。
二、绑定内联样式
(一)Attribute 绑定
语法 | 输入类型 |
---|---|
[attr.style]="styleExp" | string |
表达式结果是最终的 style 属性值。
(二)style Attribute 绑定
绑定类型 | 语法 | 输入类型 |
---|---|---|
单 style 绑定 | [style.key]="styleExp" | string | undefined | null |
带单位的单 style 绑定 | [style.key.unit]="styleExp" | number | undefined | null |
多 style 绑定 | [style]="styleExp" | string| Array<string> | |
该方法会更新 style 属性值,更新逻辑取决于结果的类型(参考 class Attribute 绑定的更新逻辑)。
(三)内置属性型指令 NgStyle 绑定
语法 | 输入类型 |
---|---|
[ngStyle]="styleExp" |
该方法会更新 style 属性值,输入类型只能是对象。其中 key 是样式名称,带有可选的单位后缀(比如 'top.px','font-style.em');value 是待求值的表达式。如果 value 不是 null,则把用指定单位表示的结果赋值给指定的样式属性;如果是 null,则删除相应的样式。
三、总结
绑定 HTML Class 的优先级为:Attribute 绑定 > Property 绑定 > 内置属性型指令 NgClass 绑定 > 内置属性型指令 NgClass 绑定。其中 Attribute 绑定和 Property 绑定会覆盖掉其他 class,必须谨慎使用。建议对于单个 class 的动态绑定使用单 class 绑定,对于多个则使用 NgClass 绑定。绑定内联样式时同理。
文中使用的工具或者包的版本:
Angular CLI 11.0.6