user1675891
user1675891

Reputation:

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

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?

Upvotes: 5

Views: 2058

Answers (3)

Vega
Vega

Reputation: 28738

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>

Upvotes: 1

Akshay Raut
Akshay Raut

Reputation: 86

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

This is the correct syntax

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658235

'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"

Upvotes: 7

Related Questions