TomP TomP - 3 months ago 32
Javascript Question

Angular 4 ngFor set class for element

I am new to Angular and I am trying to make side menu using material lists and ngFor.

<md-list-item
*ngFor="let linkItem of linkItems"
class="{{linkItem.className}}"
routerLink="{{linkItem.routerLink}}"
(click)="listItemClickToggle(linkItem)">
{{linkItem.linkName}}
</md-list-item >


everything works fine except setting
class
. IS there any different approach to do it?

app.component.ts

import { Component, OnInit } from '@angular/core';

import { LinkItem } from './link-item';

const LINK_ITEMS: LinkItem[] = [
{
linkName: 'Weather',
className: 'list-item',
routerLink: '/weather'
},
{
linkName: 'Top visits',
className: 'list-item',
routerLink: '/visits'
},
{
linkName: 'Photo Gallery',
className: 'list-item',
routerLink: '/gallery'
}
]

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})



export class AppComponent implements OnInit {
title = 'My forum';

linkItems: LinkItem[] = LINK_ITEMS;
selectedListItem: LinkItem;

constructor() {
}

ngOnInit(): void {
this.selectedListItem = null;
}

listItemClickToggle(linkItem: LinkItem): void {
console.log(linkItem);
}
}

Answer Source

You should use [ngClass] instead of just class

[ngClass]="linkItem.className"