组件装饰器主机 属性 中的 ngClass 不起作用

ngClass in host property of component decorator does not work

我创建了以下简单示例组件,它使用 @Component 装饰器的主机 属性 向组件 DOM 元素添加了一些属性和侦听器。在我的例子中 [ngClass] 是无效的。有人知道为什么以及如何解决它吗?

import { Injector, Component } from "angular2/core";
import { NgClass } from "angular2/common";
import { SelectionService } from "../selection-service";

@Component({
    selector: "my-component",
    template: `<div>inner template</div>`,
    host: {
        style: "background-color: yellow", // works
        "[ngClass]": "{'selected': isSelected}", // does not work
        "(mouseover)": "mouseOver($event)", // works
        "(mouseleave)": "mouseLeave($event)", // works
    },
    directives: [NgClass],
})
export class MyComponent {
    private isSelected = false;

    constructor(private selectionService: SelectionService) {
        this.selectionService.select$.subscribe((sel: Selection) => {
            this.isSelected = sel; // has no effect on ngClass
        });
    }

    mouseOver($event) {
        console.log("mouseOver works");
    }

    mouseLeave($event) {
        console.log("mouseLeave works");
    }
}

我正在使用 Angular 2.0.0-beta.7。

ngClass 是指令,不能用于主机绑定。主机绑定仅支持

  • 属性 '[propName]':'expr'
  • 属性'[attr.attrName]':'expr'
  • 事件 (event)="someFunction(event);otherExpr"
  • 风格[style.width]="booleanExpr"
  • class [class.className]="booleanExpr"绑定。
  • class [class]="expr" 其中 expr 是以 space 分隔的字符串 classes

这里有两种使用 @HostBinding 装饰器将宿主元素 class 绑定到 属性 的不同方法:

@HostBinding('class.enabled') private get isEnabled() { // use getter to reflect external value
    return this.selectionService.state.isEnabled;
}
@HostBinding('class.selected') private isSelected = false; // setting this add/removes 'selected' class

constructor(private selectionService: SelectionService) {
    this.selectionService.select$.subscribe(isSelected => {
        this.isSelected = isSelected;
    });
}

这对我有用,而且非常模块化:

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

type Directions = 'vertical' | 'horizontal'

/**
 * A hairline.
 */
@Component({
  selector: 'hairline',
  styleUrls: ['./hairline.component.scss'],
  template: '',
})
export class HairlineComponent {
  @Input() direction: Directions = 'horizontal'
  @Input() padding = false

  @HostBinding('class')
  get classes(): Record<string, boolean> {
    return {
      [this.direction]: true,
      padding: this.padding,
    }
  }
}