Search code examples
angularng-class

how to understand angular ng-class and dynamic class


I try to use ng-class, I need to create dynamic class in angular. But can't find some easy and clear for me tutorial or something like that.

For example I have something like that: app.template.html

<div class="items-container" >
    <ul>
        <li class="item" *ngFor="let tag of tags">
            <div class="icon" ng-mouseenter="mouseEnter(tag.name)">
                <img src="/assets/{{tag.icon}}" />
            </div>
            <div ngClass="{'show' : false, 'hide' : true, 'tag-name'}">
                {{tag.name}}
            </div>
        </li>
    </ul>

</div>

app.ts

export class AGmainMenu {

    tags = mainMenuItems[0].tags;
    itemShow: false;

    mouseEnter(tag){
        console.log("mouse enter : ", this, tag);
    }
}

And I want that after mouseenter on div.icon, sibling div (.tag-name) change class from hide to show. And I really don't know how to connect changing class with function mouseEnter.


Solution

  • In the base, it works like:

    • You create some class (css/scss)
    • You bind that class dynamicly to your html element based on some condition.

    Example

    isBlack = true;
    div.my-dynamic-class {
      background-color: #000000;
      }
    <div [ngClass]="{'my-dynamic-class': isBlack}"></div>

    where isBlack would be the boolean based on that class will be applied.

    Here is the complete documentation: LINK