Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngClass in host property of component decorator does not work

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.

like image 699
Holger Stitz Avatar asked Mar 02 '16 16:03

Holger Stitz


2 Answers

ngClass is a directive and can't be used in host bindings. Host bindings only supports

  • property '[propName]':'expr'
  • attribute '[attr.attrName]':'expr'
  • event (event)="someFunction(event);otherExpr",
  • style [style.width]="booleanExpr"
  • class [class.className]="booleanExpr" binding.
  • class [class]="expr" where expr is a string with space separated classes
like image 60
Günter Zöchbauer Avatar answered Sep 21 '22 18:09

Günter Zöchbauer


Here 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;
    });
}
like image 20
Mayfield Avatar answered Sep 19 '22 18:09

Mayfield