Search code examples
htmlangularscss-lint

Angular: Accessing Variables in a Function


I'm not sure how to access "this" from a function in Angular.

This is my HTML

    <img id="castle_frame_0" [ngClass]="this.frame == 0 ? 'show' : 'hide'" src="../../assets/FC_Frame_0.png">
    <img id="castle_frame_1" [ngClass]="this.frame == 1 ? 'show' : 'hide'" src="../../assets/FC_Frame_1.png">
    <img id="castle_frame_2" [ngClass]="this.frame == 2 ? 'show' : 'hide'" src="../../assets/FC_Frame_2.png">
    <img id="castle_frame_3" [ngClass]="this.frame == 3 ? 'show' : 'hide'" src="../../assets/FC_Frame_3.png">
    <img id="castle_frame_4" [ngClass]="this.frame == 4 ? 'show' : 'hide'" src="../../assets/FC_Frame_4.png">
    <img id="castle_frame_5" [ngClass]="this.frame == 5 ? 'show' : 'hide'" src="../../assets/FC_Frame_5.png">

I'm basically trying to change the frames every X seconds to make one of the characters blink. This is my component so far: enter image description here

Help is much appreciated!


Solution

  • It's basically the approach you have described, you just need to put it into your code. Below is one way you can do it

    export class HomeComponent implements OnInit {
      frame = 0;
      refresh = 2000;
      maxFrames = 5;
    
      constructor() {
        setInterval(() => {
          this.blink()
        }, this.refresh); // will call the blink function after every 2 seconds
      }
    
      ngOnInit() {
        this.frame = 1; 
        console.log(this.frame);
      }
    
      blink() {
        // If frame is 0 then set it to some other number between 1 and 5 else set it back to 0;
        this.frame = this.frame === 0 ? this.getRandom(1, this.maxFrames)  : 0;
      }
    
      getRandom(min: number, max: number){
        return Math.floor(Math.random() * (max - min + 1) + min);
      }
    }
    

    After every 2 seconds it will change to 0 and stay 0 for 2 seconds then change to a random number between 1-5 and stay that for 2 seconds.

    Here is a Stackblitz Demo where you can play with this code and see this in action