简体   繁体   中英

Javascript/Angular: timeout wrapped in function not workink with boolean value

In the View I have this condition:

    <h3 *ngIf="show">{{users.result}}</h3>

In the TypeScript logic I have:

show=false; <----as a property

And the the following function:

timeOut(seconds: number, value:boolean) {
   value = true;      
    setTimeout(
      function() {
        value = false;
      }.bind(this),
      seconds
    );
  }

But when I call it, like this:

console.log(this.timeOut(3000, this.show));

the property `this.show´ gets undefined, but the seconds passed as argument work. I'm missing something and I can't figure out what... Can anyone give a help?

As i see:

  • First of all you console logging function call without result .
  • When you pass the boolean value into the function params it's being copied , so when you change the value inside the function, it doesn't affect the outside variable/field.
  • This is very specialized use case, so you do not need to extract it to different function.

My suggestion - just put setTimeout call with arrow function into some component's method like ngAfterViewInit or in event handler method :

ngAfterViewInit() {
   setTimeout(() => this.show = true, 3000)
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM