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

淺唱寂寞╮ 提交于 2019-12-10 16:00:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!