ngClass 插值不起作用

ngClass interpolation not working

考虑以下图标组件。为什么 color 变量保留为单词颜色而不是进行插值?

import {Component, Input, OnInit} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'nui-icon',
  template: `
    <i class="material-icons" 
       [ngClass]="{color: true, 'bordered': border}"
       [ngStyle]="{'font-size':size + 'px'}">
      <ng-content></ng-content>
    </i>
  `,
  styles: [`
    i {
      display: inline-flex;
    }
    i.bordered {
      border: 1px solid #d8d8d8;
      border-radius: 50%;
      padding: 15px;
    }
  `]
})

export class NuiIconComponent implements OnInit {
  @Input() color: string;
  @Input() size: string = '24';
  @Input() border: boolean = false;

  constructor () {}

  ngOnInit () {
  }
}

ngClass接受三种类型的表达式

  1. 字符串表达式
  2. 数组表达式
  3. 对象表达式n

您使用的是对象表达式。在对象表达式中,键是 CSS 类,当值中给定的表达式的计算结果为真值时,键将被添加,否则它们将被删除。因此,key 将始终被视为字符串,而不是表达式。

为了您的目的,您可以使用如下字符串表达式。

[ngClass]="color"

[class]="color"

参考:Angular ngClass API doc

您可以像这样传递字符串表达式:

[ngClass]="(border ? 'bordered ' : '') + color"

或使用 class 绑定 color

[ngClass]="{ bordered: border }" [class]="color"