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

Hol*_*itz 12 angular2-template angular

我创建了以下简单的示例组件,它使用@Component装饰器的host属性向组件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');
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 22

ngClass是一个指令,不能在主机绑定中使用.主机绑定仅支持

  • 属性 '[propName]':'expr'
  • 属性 '[attr.attrName]':'expr'
  • 事件(event)="someFunction(event);otherExpr",
  • 样式 [style.width]="booleanExpr"
  • [class.className]="booleanExpr"绑定.
  • class [class]="expr"where expr是一个包含空格分隔类的字符串

  • 感谢您的回答。在我特定的ngClass案例中,我添加了有效的`[class.selected] =“ isSelected”`。 (2认同)

May*_*eld 6

以下是使用装饰器将宿主元素类绑定到属性的两种不同方法@HostBinding

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

constructor(private selectionService: SelectionService) {
    this.selectionService.select$.subscribe(isSelected => {
        this.isSelected = isSelected;
    });
}
Run Code Online (Sandbox Code Playgroud)