0

Can't believe I am asking this, but I did not find an answer to this problem. As you can guess I am fairly new to Angular.

How can I change public slideNumber = 1 dynamically within a class?

    export class TestimonialComponent {
  public slideNumber = 1;

  Carousel() {
    setInterval(function () {
      this.slideNumber = 9;
    }, 1000);
  }

  ngOnInit(): void {
    this.Carousel();
    this.slideNumber = 3;
  }
}

from my understanding ngOnInit shares slideNumber with the class, but the Carousel function declares its own slideNumber.

My question is why does this happen and how can I dynamically change the first declared variable in the class? (public slideNumber = 1)

Clarification

  • ngOnInit changes the public slideNumber = 1 to 3
  • Carousel function creates it's own property this.slideNumber = 9

This means that public slideNumber = 1 is now 3 and Carousel is not able to interact with public slideNumber = 1

Stanley
  • 2,434
  • 18
  • 28
  • `ngOnInit` is a lifecycle hook, not sure what you mean about "shares slideNumber with the class". Is `Carousel` just a function? Need more info and preferrably a reproducible example (template code etc) – Phix Jul 01 '20 at 18:01
  • @Phix Thanks for reaching out! yes Carousel is just a function. However, the Carousel's `this.slideNumber` is independent from the class's `public slideNumber = 1` Does that help? if not i will provide some more information. – Stanley Jul 01 '20 at 18:03

2 Answers2

3

change Carousel to

Carousel() {
    setInterval(() =>{
      this.slideNumber = 9;
    }, 1000);
  }

When using function(){} , it makes a new this that depends on how it being called. when using arrow syntax () => {}, this is same as parent's.

For more info, check out https://itnext.io/the-this-keyword-in-javascript-demystified-c389c92de26d

R Pasha
  • 700
  • 5
  • 21
  • Hmm, i see! thank you! Would you care to add an explanation? – Stanley Jul 01 '20 at 18:09
  • @Stanley, ur welcome. I just updated my answer. – R Pasha Jul 01 '20 at 18:11
  • Thank you! This is embarrassing, I guess you live and learn. Great explanation! I will accept the answer once the timer goes out – Stanley Jul 01 '20 at 18:12
  • @Stanley. Always consider using es6 syntax in Angular. – Akhil Jul 01 '20 at 18:22
  • @Akhil yeah, this was totally my bad! I forgot how to setInterval and found and old article and just copied the first thing I found. And I was certain this problem was caused by angular syntax I didn't know haaha. – Stanley Jul 01 '20 at 18:24
0

make slideNumber an @Input variable. or add a method

setSlideNumber(num:number) {
  this.slideNumber = num;
}

and then use a ViewChild to set it. there's no reason to have hard coded numbers in your code.

Rick
  • 1,710
  • 8
  • 17