3

ngClass directive generating the following error

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngClass' since it isn't a known property of 'li'.

code snippet.

 <li [ngClass]="{'active':true}"><a href="">Home</a></li>

NB: I already imported the common module

import {CommonModule} from "@angular/common"

Library version angular 4.0.1

AT82
  • 71,416
  • 24
  • 140
  • 167
Binson Eldhose
  • 993
  • 3
  • 14
  • 35
  • did you included the module aswell in the app.module imports part? – Daniel Netzer Jun 03 '17 at 21:21
  • 1
    If the component under the root module make sure that BrowserModule is imported. If it is in a child module import CommonModule. These imports being missing will give you that error when trying to use common directives. – Nedim Hozić Jun 03 '17 at 21:39

1 Answers1

8

As @Nedim suggested, if you are using [ngClass] within a feature module, you'd need to make sure that CommonModule is being added to the imports: [] array property of @NgModule({}):

import {CommonModule} from "@angular/common"

@NgModule({
    imports: [CommonModule]
})
export class SomeModule {}

To conditionally add a single class based on a boolean value/expression I'd recommend you use the syntax [class.someClass]="condition". Here is the documentation for Class binding.

<li [class.active]="true"><a href="">Home</a></li>

For example, to evaluate against a boolean class property to conditionally apply "active" CSS class:

TS:

export class App {
  foo: boolean = true;
}

HTML:

<div [class.active]="foo">Foobar</div>

Here is a plunker demonstrating the functionality in action.

Note: If you are trying to apply some type of active styling related to the router, you could use the RouterLinkActive binding. The following example would apply the CSS class "active" when the user has activated the path "/heroes".

<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • I'd imagine it's related to not having `CommonModule` added to `imports: []` of the feature module where `[ngClass]` is being used. I've updated to answer to suggest that addition. Probably will need more information from @Binson. – Alexander Staroselsky Aug 08 '17 at 16:38