我创建了以下简单的示例组件,该组件使用@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');
}
}
我正在使用Angular 2.0.0-beta.7。
答案 0 :(得分:19)
ngClass
是一个指令,不能用于主机绑定。主机绑定仅支持
'[propName]':'expr'
'[attr.attrName]':'expr'
(event)="someFunction(event);otherExpr"
,[style.width]="booleanExpr"
[class.className]="booleanExpr"
绑定。[class]="expr"
其中expr
是一个包含空格分隔类的字符串答案 1 :(得分:1)
以下是使用@HostBinding
装饰器将主机元素类绑定到属性的两种不同方式:
@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;
});
}
答案 2 :(得分:0)
这对我有用,并且非常模块化:
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,
}
}
}