Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Check the Class of an Element

I want to access the class of an element to check if it is "collapse in" or "collapse". I want to do something like:

<span *ngIf=" class == 'collapse in' "> - </span>
<span *ngIf=" class == 'collapse'    "> + </span>

Is there a simple way to get the class of an element on Angular2?

like image 350
Bünyamin Sarıgül Avatar asked Dec 19 '22 13:12

Bünyamin Sarıgül


1 Answers

Usually in Angular2 the setup should be the other way around, the model is updated and the view reflects the model. This way you don't need to access the DOM to check it's state. However if you must this should do:

<span #span *ngIf="hasClass(span.className, 'collapse') && hasClass(span.className, 'in')"> - </span>
<span #span *ngIf="hasClass(span.className, 'collapse')"> + </span>
hasClass(classes, cls) {
    return (' ' + classes + ' ').indexOf(' ' + cls + ' ') > -1;
}

https://developer.mozilla.org/de/docs/Web/API/Element/className

or

<span #span *ngIf="span.classList.contains('collapse') && span.classList.contains('in')"> - </span>
<span #span *ngIf="span.classList.contains('collapse')"> + </span>
like image 188
Günter Zöchbauer Avatar answered Dec 29 '22 08:12

Günter Zöchbauer