4

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!!!) : )

ct5845
  • 1,428
  • 3
  • 16
  • 20

2 Answers2

4

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
-1

I had same issue but i could solve it importing some modules on my module:

import { RouterModule, Routes }   from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {KSSwiperModule} from 'angular2-swiper';

import { DashboardComponent }     from './dashboard.component';
import {SwiperComponent} from "./swiper.component";

const routes: Routes =  [
  { path: 'dashboard',  component: DashboardComponent },
];

@NgModule({
  imports:      [
    RouterModule.forChild(routes),
    KSSwiperModule,
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  declarations: [ DashboardComponent, SwiperComponent ]
})
export class DashboardModule { }

and my component doesn't use "host":

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  moduleId: "dashboard",
  selector: 'app-dashboard',
  templateUrl: 'dashboard.component.html',
  styleUrls: [ 'dashboard.component.scss' ],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent {
  public isLandingHidden: boolean;

  showReasons() {
    this.isLandingHidden = true;
  }
}
Luiz Mitidiero
  • 1,130
  • 1
  • 10
  • 22