angular 2 中 ngClass 中的动态类名 [英] Dynamic classname inside ngClass in angular 2

查看:72
本文介绍了angular 2 中 ngClass 中的动态类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 ngClass 表达式中插入一个值,但我无法让它工作.

I need to interpolate a value inside of an ngClass expression but I can't get it to work.

我尝试了这些对我来说唯一有意义的解决方案,这两个在插值时失败了:

I tried these solution which are the only ones that makes sense to me, these two fails with the interpolation:

<button [ngClass]="{'{{namespace}}-mybutton': type === 'mybutton'}"></button>
<button [ngClass]="{namespace + '-mybutton': type === 'mybutton'}"></button>

这个适用于插值,但在动态添加的类中失败,因为整个字符串被添加为一个类:

This one works with the interpolation but fails with the dynamically added class because the entire string gets added as a class:

<button ngClass="{'{{namespace}}-mybutton': type === 'mybutton'}"></button>

所以我的问题是你如何像这样在 ngClass 中使用动态类名?

So my question is how do you use dynamic classnames in ngClass like this?

推荐答案

试试

<button [ngClass]="type === 'mybutton' ? namespace + '-mybutton' : ''"></button>

相反.

<button [ngClass]="[type === 'mybutton' ? namespace + '-mybutton' : '']"></button>

甚至

<button class="{{type === 'mybutton' ? namespace + '-mybutton' : ''}}"></button>

会起作用,但使用 ngClass 的额外好处是它不会覆盖由任何其他方法添加的其他类(例如:[class.xyz] 指令或 class 属性等)与 class 一样.

will work but extra benefit of using ngClass is that it does not overwrite other classes that are added by any other method( eg: [class.xyz] directive or class attribute, etc.) as class does.

新的编译器 Ivy 使同一元素上存在不同类型的类绑定时会发生什么情况更加清晰和可预测.在此处阅读更多相关信息.

The new compiler, Ivy, brings more clarity and predictability to what happens when there are different types of class-bindings on the same element. Read More about it here.

ngClass 接受三种类型的输入

ngClass takes three types of input

  • Object:每个key对应一个CSS类名,不能有动态key,因为key 'key' key" 都是一样的,[key] 不支持 AFAIK.
  • 数组:只能包含类列表,没有条件,尽管三元运算符有效
  • 字符串/表达式:就像普通的类属性
  • Object: each key corresponds to a CSS class name, you can't have dynamic keys, because key 'key' "key" are all same, and [key] is not supported AFAIK.
  • Array: can only contain list of classes, no conditions, although ternary operator works
  • String/ expression: just like normal class attribute

这篇关于angular 2 中 ngClass 中的动态类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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