Angular 2动态添加类

时间:2016-11-23 10:51:22

标签: angular

拥有此模板:

<li role="menu" class="drop-down">
  <a class="drop-down--toggle">
    <span class="flag-icon" [class]="_current.flag"//<-- don't work></span>
  </a>
  <ul class="drop-down--menu>
  ...
  </ul>
</li>

和这个模型:

export class LocaleModel {
  id: number;
  code: string;
  name: string;
  fileName: string;
  flag: string;// <-- could be "flag-icon-es" or "flag-icon-gb"

  constructor(id: number, code: string, name: string, fileName: string, flag: string) {}
  }

期望的最终效果是:

<li role="menu" class="drop-down">
  <a class="drop-down--toggle">
    <span class="flag-icon flag-icon-es"></span>
  </a>
  <ul class="drop-down--menu">
  ...
  </ul>
</li>

是否可以动态添加类的一部分,或者我应该保存整个类名,例如&#34; flag-icon flag-icon-es&#34;并添加整个?

1 个答案:

答案 0 :(得分:3)

使用ngClass,如下所示:

<span class="flag-icon" [ngClass]="[_current.flag]"></span>