Can't assign [ngClass] to Angular components generated by *ngFor loop
Asked Answered
G

3

5

I'm trying to follow an example showing how to bind a class active to a component when it's clicked. When I execute the code based on the markup below

<div *ngFor="let menu of menus;"
     [id]="menu.id"
     (click)="onClick($event,menu.link)"
     [ngClass]="'active':menu.active"
     class="navigator">
  {{menu.title}}
</div>

I get the following error. NB - there's onClick(...) method in the component and at the moment I commented out all its contents. The error seems to be purely related to the markup (unless I need to declare something extra in the component, like an array or such). At least as far I've seen the examples while googlearching this issue.

Uncaught Error: Template parse errors:
Parser Error: Unexpected token ':' at column 9 in ['active':menu.active] in ng:///AppModule/NavigatorComponent.html@11:9 ("
[id]="menu.id"
(click)="onClick($event,menu.link)"
[ERROR ->][ngClass]="'active':menu.active"
class="navigator">
{{menu.title}}
"): ng:///AppModule/NavigatorComponent.html@11:9

What am I missing?

Gymnasiarch answered 21/8, 2017 at 7:56 Comment(0)
C
7

'active':menu.active isn't a valid expression.

User either the object literal syntax

[ngClass]="{'active':menu.active}"

or the string syntax

[ngClass]="menu.active ? 'active' : null"

or

[class.active]="menu.active"
Curlew answered 21/8, 2017 at 7:58 Comment(0)
H
1

An other approach in this case, could be using [class] property, because it could be more concise, as pointed out by @Günter Zöchbauer:

 <div *ngFor="let menu of menus;"
     [id]="menu.id"
     (click)="onClick($event,menu.link)"
     [class.active]="menu.active"
     class="navigator">
  {{menu.title}}
</div>
Hanuman answered 21/8, 2017 at 7:58 Comment(3)
Hmm... How doe sit relate to [ngClass]? Are we talking just different syntaxes or a totally different approach?Gymnasiarch
It has the same effect but it is more concise than using ngClass. ngClass is for more complex scenarios.Tomekatomes
Sorry, must have said, an other approach :) easier to write and shorter?Hanuman
I
0
[ngClass]="{'active':menu.active}"

This is the correct syntax

Intrinsic answered 21/8, 2017 at 8:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.