ngClass可以在Angular 2中使用三元运算符吗? [英] Can ngClass use ternary operator in Angular 2?

查看:472
本文介绍了ngClass可以在Angular 2中使用三元运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 1中,下面的代码运行良好.

In Angular 1, the code below works well.

<div ng-class="$varA === $varB ? 'css-class-1' : 'css-class-2'">

但是当我尝试在Angular 2中做类似的事情时,这是行不通的.

But when I try to do similar thing in Angular 2. It does not work.

我已经添加了directives: [NgClass]

<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">

我应该如何用Angular 2编写,谢谢!

How should I write in Angular 2, thanks!

这是我的错误,我无意中将{ }添加到了整个varA === varB ? 'css-class-1' : 'css-class-2'中.因此ngClass仍可以在Angular 2中使用三元运算符.

It was my mistake, I accidentally added { } to the whole varA === varB ? 'css-class-1' : 'css-class-2'. So ngClass still can use ternary operator in Angular 2.

推荐答案

是.您写的作品有效:

<div [ngClass]="varA === varB ? 'css-class-1' : 'css-class-2'">

柱塞

右侧表达式的结果必须计算为以下值之一:

The result of the expression on the the right-hand side has to evaluate to one of the following:

  • 一串用空格分隔的CSS类名(这是您的表达式返回的内容)
  • 一组CSS类名称
  • 一个对象,以CSS类名作为键,布尔值作为值

也许您的代码中还有其他错误?

Maybe you had some other error in your code?

这篇关于ngClass可以在Angular 2中使用三元运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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