a-k-h
a-k-h

Reputation: 387

(Angular 6) Dynamically add style to element inside the one that was clicked. Rotate chevron

I want to rotate chevron when the button is clicked. So my question would be - how to do it? Should I add the whole Angular animation component and do it there or is it possible to just add rotate to just a chevron?

<a href="#" (click)="transformArrow()">Show
   <span>
       <label class="m-0">this</label>
       <span class="glyphicons glyphicons-chevron-down" id="myElement"></span>
   </span>
</a>

then I tried to add some function

transformArrow(){
    let ele = document.getElementById('myElement');
    ele.style.transform  //And I stuck here as I need to actually access ":before" of this element and rotate it.
}

Huge thanks to trichetriche and malbarmawi for alternative, only thing that I had to change was "after" to "before" :)

My idea is:

transformArrow(e) {
    let ele = document.getElementById('myElement');

        ele.classList.toggle('btn-change');


}


.glyphicons-chevron-down
    {
        transition: $trans-1;

        &.btn-change
        {
            &:before
            {
                position: relative;
                display: block;
                transform: rotate(180deg);
            }

        }
    }

I really like the idea with ngClass but I like to keep most of actions in component.ts so i wanted to stay with function. Is it even good, or maybe it's better practice to do it the way malbarmawi did?

Upvotes: 1

Views: 4144

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24472

You can use ngStyle directive

<a href="#" (click)="toggle = !toggle">Show
   <span>
    <label class="m-0">this</label>
    <span [ngStyle]="{'transform': toggle ? 'rotate(180deg)':''}" class="fa fa-arrow-right"></span>
   </span>
</a>

another way ngClass directive

<a href="#" (click)="toggle = !toggle">Show
   <span>
       <label class="m-0">this</label>
       <span [ngClass]="{'flip-h': toggle}" class="fa fa-arrow-right fa-2x"></span>
   </span>
</a>

or with element reference (not recommended)

<a href="#" (click)="elem.classList.toggle('flip-h')">Show
   <span>
       <label class="m-0">this</label>
       <span #elem  class="fa fa-arrow-right fa-2x" id="myElement"></span>
   </span>
</a>

demo

Upvotes: 1

user4676340
user4676340

Reputation:

Why not do it through CSS and custom attributes ?

ele.setAttribute('data-rotate', 'true')
span#myElement[data-rotate="true"]:after {
  transform: rotate(90deg);
}

Upvotes: 2

Related Questions