(角度6)在元素中动态添加样式。旋转人字形

时间:2018-10-23 13:39:05

标签: css angular angular6

我想在单击按钮时旋转人字形。所以我的问题是-怎么做?我应该在其中添加整个Angular动画组件并在其中做,还是可以只将旋转添加到V形?

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

然后我尝试添加一些功能

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.
}

非常感谢trichetriche和malbarmawi的替代,我唯一需要更改的是“之后”到“之前” :)

我的想法是:

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);
            }

        }
    }

我真的很喜欢ngClass的想法,但是我想将大部分动作保留在component.ts中,所以我想继续使用功能。这样做还是更好,或者像马尔巴马维那样做是更好的做法?

2 个答案:

答案 0 :(得分:1)

为什么不通过CSS和自定义属性呢?

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

答案 1 :(得分:0)

您可以使用ngStyle指令

<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>

另一种ngClass指令

<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>

或带有元素引用(不推荐

<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