ng-class in Angular2


I am developing a test application in angular 2 and I'm stuck with a problem of adding classes based on list from model.

In Angular 1 one could do:

// model
$scope.myClasses = ['class1', 'class2', ...];

// view
... ng-class="myClasses" ...

In Angular 2, all I have been able to do so far is:

// view
... [class.class1]="true" [class.class2]="true" ...

Which is obviously not very dynamic and I'm sure there must be a better way to do this.

However, I have also tried:

// model
class ... {
    private myClasses: any;
    constructor() {
        this.myClasses = ['class1', 'class2', ...];

// view
... [class]="myClasses" ...

but this doesn't work, I have tried myClasses as a string name of a single class, array of strings, object with a classname key and true as a value, an array of objects of this kind, but sadly, nothing of listed will work this way.


I was trying to do something similar, I had a list of menu items and wanted to specify a fontawesome class for each item. This is how I made it work. In my typescript component I had this:

    export class AppCmp {
       menuItems = [
           text: 'Editor',
           icon: 'fa fa-pencil'
           text: 'Account',
           icon: 'fa fa-user'
           text: 'Catalog',
           icon: 'fa fa-list'

Then in my html:

By : Will

This video can help you solving your question :)
By: admin