How to get the current classes of an element in an Angular directive

核能气质少年 提交于 2019-12-25 01:42:55

问题


I have to make an Angular 7 directive where I can toggle (add/remove) a class from the element (ElementRef). When the class in not in the element add it, and when it's in the element remove it.

I know how to add / remove a class ... but how to get the current classes of an element ? ... so I can check if I have to add or remove


回答1:


To get the current classes of an element, you could do:

    const elementRef: ElementRef;
    const classes = elementRef.nativeElement.classList;
    if (classes.contains('your class')
    {
       // do something
    }





回答2:


You can inject an ElementRef in the directive constructor and and access the classes of the element on which directive is applied using

this._el.nativeElement.getAttribute('class')

Where this._el is the injected ElementRef.

See an example here:

https://stackblitz.com/edit/angular-bo6xtg



来源:https://stackoverflow.com/questions/55851815/how-to-get-the-current-classes-of-an-element-in-an-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!