Search code examples
angularng-class

Angular2 Exception: ngClass within a Host, "isn't a known native property"


Is it possible to use "ngClass" within the host for a component/directive.

    @Component({
        selector: 'custom',
        template: `<div [ngClass]="classMap"></div> // I work
        <ng-content></ng-content>`,
        host: {
            '[ngClass]' : 'classMap' // I don't work!!!
        }
    })
    export class CustomComponent {
        constructor () {
            this.classMap = {
                custom: true
            };
        }
    }

In the above example the ngClass works correctly on the div in the template.. it get's a "custom" class added, but it throws an exception when trying to add via to the Host.

"Can't bind to 'ngClass' since it isn't a known native property"

Setting the class in the host directly works fine e.g.;

host: {
    '[class.custom]' : 'classMap.custom'
}

Therefore would think ngClass would be ok? Incorrect syntax? (likely!!!) : )


Solution

  • ngClass is a directive and directives are not supported in host bindings.

        host: {
            '[ngClass]' : 'classMap' // I don't work!!!
        }
    

    would need to be

        host: {
            '[class.className]' : 'className', 
            '[class]' : 'classNames' 
        }
    

    where classNames is a space separated list of classes.