Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf check if class exists on element

Tags:

Is there any way to use *ngIf to check if element has certain class? I tried using

<img *ngIf="[class.imgView]" class="imgView" src="..">

which threw error cannot read property imgView of undefined.

Is there any way how to achieve so with angular?

like image 584
Darlyn Avatar asked Aug 03 '16 12:08

Darlyn


1 Answers

Make a function that returns the class you need if some boolean is true:

returnClass = true;
getClass() {
    if(this.returnClass) {
        return "myView";
    } else {
        return "";
    }
}

and change your view:

<img *ngIf="returnClass" [ngClass]="getClass()" src="..">

Now if returnClass is true, you know that your img will have the desired class, so you can pass returnClass into *ngIf

You could also remove the class by: this.returnClass = false which would also hide the element.

This would become tedious with many classes, but will be reasonable for a few.

like image 115
theblindprophet Avatar answered Sep 28 '22 03:09

theblindprophet