问题
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!!!) : )
回答1:
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.
回答2:
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;
}
}
来源:https://stackoverflow.com/questions/35895703/angular2-exception-ngclass-within-a-host-isnt-a-known-native-property