I created the following simple example component that adds some attributes and listener to the component DOM element using the host property of the @Component decorator. In my case [ngClass] is has no effect. Does someone know why and how to fix it?
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");
}
}
I'm using Angular 2.0.0-beta.7.
ngClass
is a directive and can't be used in host bindings. Host bindings only supports
'[propName]':'expr'
'[attr.attrName]':'expr'
(event)="someFunction(event);otherExpr"
, [style.width]="booleanExpr"
[class.className]="booleanExpr"
binding.[class]="expr"
where expr
is a string with space separated classesHere are two different ways to bind a host element class to a property using the @HostBinding
decorator:
@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;
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With