Angular2 ngClass:如何有条件地选择一个班级?

时间:2017-04-09 10:00:30

标签: angular angular2-template angular2-directives

我在Angular 2中有以下代码。我希望只有一个div元素将获得一个类样式'选择'基于' service.mode'的价值。编写完这段代码之后,我发现所有的div元素都会被选中"选择",即使' service.mode'等于'插槽'。

<header>
  <div [ngClass] = "{'chosen': 'service.mode == \'featured\''}"> Featured Games</div>
  <div [ngClass] = "{'chosen': 'service.mode == \'slots\''}"> Slot Games </div>
  <div [ngClass] = "{'chosen': 'service.mode == \'card\''}"> Card Games </div>
  <div [ngClass] = "{'chosen': 'service.mode == \'table\''}"> Table Games </div>
</header>

你知道可能是什么问题吗?

1 个答案:

答案 0 :(得分:1)

正确的语法是:

<header>
    <div [ngClass] = "{'chosen': service.mode == 'featured'}"> Featured Games</div>
    <div [ngClass] = "{'chosen': service.mode == 'slots'}"> Slot Games </div>
    <div [ngClass] = "{'chosen': service.mode == 'card'}"> Card Games </div>
    <div [ngClass] = "{'chosen': service.mode == 'table'}"> Table Games </div>
</header>

如果您想将\''进行比较,请不要知道您使用service.mode的原因,在featured\内使用它。