6

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?

Udara
  • 176
  • 10
Darlyn
  • 4,715
  • 12
  • 40
  • 90
  • Why do you want to do this? Classes are not generally something that you use to store state, and retrieve and then do something conditionally based on whether or not they exist. They are used to apply CSS styling. If you want to maintain state, maintain state in your component. –  Aug 03 '16 at 12:51
  • I have a component which contains a lot of images. I want browser to load img only after they have been scrolled into view. This was what came to my mind as first being newbie in angular2 – Darlyn Aug 03 '16 at 12:53

3 Answers3

3

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.

theblindprophet
  • 7,767
  • 5
  • 37
  • 55
1

Here is a quick solution:

@Component({
    selector: 'app',
    template: `
      <p class="imgView test" #test [hidden]="hasClass(test)">shown</p>
      <p #test1 [hidden]="hasClass(test1)">hidden</p>
      <p class="imgView" #test2 [hidden]="hasClass(test2)">shown</p>`
})
export class App {
  hasClass(el: any) {
    return !(el.getAttribute('class') && el.getAttribute('class').indexOf('imgView') !== -1);
  }
};

I've replaced *ngIf with [hidden] because *ngIf doesn't work with this approach, but you should use [hidden] in this scenario any way.

Here is the plunker

If you need to use this in ngFor for example this is how you would do it:

ng2: How to create variable in ngFor loop

Community
  • 1
  • 1
Filip Lauc
  • 2,989
  • 1
  • 17
  • 29
0

This example might help:

Hi, we are <span [style.color]="inputElement.value === 'yes' ? 'blue' : ''"> {{name}} </span>
    <br>
    <br>
    <span [class.purple]="isPurple.value === 'lila'">Colorful</span>
    <input type="text" #isPurple (keyup)="0">
    <span [class.is-awesome]="inputElement.value === 'yes'">Is it awesome?</span>
    <input type="text" #inputElement (keyup)="0"><br>
    <button [disabled]="inputElement.value !== 'yes'">Only enabled if 'yes' was entered</button>
    <br>
zgue
  • 3,793
  • 9
  • 34
  • 39
Kriss
  • 326
  • 1
  • 3
  • 12