Search code examples
vmware-clarity

How can I animate an icon?


I have an icon tag in html as:

<clr-icon 
  [attr.shape]="open ? (iconOpen ? iconOpen : 'caret up') : (iconClose ? iconClose : 'caret down')"
  ></clr-icon>

I tried applying a transition in CSS like this:

clr-icon {
   transition: all 2s ease-in-out;
}

But it doesn't animate.


Solution

  • By writing:

    <clr-icon [attr.shape]="open ? 'caret up' : 'caret down'"></clr-icon>
    

    you're not binding to the direction, you're binding to the shape itself. This means whenever Angular updates that binding, it'll force the icon to re-render a brand new shape.

    What you want is simply to bind the direction, and keep the shape constant:

    <clr-icon shape="caret" [attr.dir]="open ? 'up' : 'down'"></clr-icon>
    

    You can see it working fine here: https://stackblitz.com/edit/clarity-animate-icon?file=src/app/app.component.html