Search code examples
cssangularstylessemantic-uing-class

Angular2: how to add/change class to element on certain conditions


I'm developing a web application with Angular and Semantic-UI framework.

For adding a class to element on certain condition I have already used the following way:

[class.className]='condition'

Now I have more than one class name and I can't figure out how to deal with it.

So I tried to use ngClass as showed in this Plunker. As you can see here this solution doesn't work at all.

So, how to fix my Plunker to make it working?


Solution

  • You can build a string containing several classes using [ngClass] here.

    <div [ngClass]="('firstClass ' + (active ? 'secondClass' : ''))"></div>
    

    In this case firstClass is the first class and active is a boolean that sets the secondClass class.

    So, in your case your code can become:

    <div class="field">
        <label for="name">Name:</label>
        <div class="ui input" [ngClass]= "((myForm.controls.name.pending ? 'loading' : '') + 'secondClass')">
            <input id="name" [formControl]="myForm.controls.name">
        </div>
    </div>
    

    Remember to provide spaces between two consecutive classes.

    EDIT

    As for your plunker, you have got to add the ngClass statement as:

    [ngClass]="[o.order === 'asc' ? 'chevron circle up': '' , o.order === 'desc' ? 'chevron circle down': '']"