Question:
How to access variables in a function using Angular?

Problems

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!


Solutions

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


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers