简体   繁体   中英

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);
  }
}

您应该使用[ngClass]而不是class

[ngClass]="linkItem.className"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM