0

I am trying to learn the concept of promise and implement in angular. Here is my code in stackblit. What I am trying to achieve is , I have want to show the array whenever it is assigned with any value using promise in angular.

My Html Code is :

<h2>Array values</h2>
<p *ngIf="show">
  <span *ngFor="let values of filter">
    {{values}}
  </span>
</p>  

My TS file is :

filter = [];
show = false;
ngOnInit() {
  this.showArray();
}
showArray() {
    var a = new Promise(resolve=>{
      setTimeout(() => {
        this.filter = [3, 4, 4]
        resolve('resolved');
      }, 0);

    });

    a.then(function() {
      this.show= true;
    })
}

Whenever my array is assigned with any values(which might be from a remote API), I want to set the variable show to true. I am not getting the result. I have gone through many examples related to promise but couldn't found a working example of promise in this fashion.

Udit Gogoi
  • 675
  • 2
  • 11
  • 28
  • 2
    Everything seems to be fine. Just change your then block to like -> a.then((func) => { this.show= true; }) – Raj Nov 15 '18 at 12:36
  • How this is a duplicate ?? – Udit Gogoi Nov 15 '18 at 12:47
  • It is a duplicate because it is the same problem, with the same solutions, as in the reference post. That question is asked every day on the Angular forum, and doesn't need more duplicate answers. – ConnorsFan Nov 15 '18 at 12:53

1 Answers1

1

Replace your code with -

a.then(() => {
  this.show= true;
})

you need to use arrow function instead of existing one.

If you are using this piece of code -

a.then(function() {
  this.show= true;
})

this will not bind to show variable which is of class level but template binding is done with class level variable, that is why existing code is not working.

Working Example

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215