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