naveen
naveen

Reputation: 937

How to update property in angular?

I am trying to update property after some time .but it is not reflecting on view why ?

Here is my code:

https://stackblitz.com/edit/angular-grjd1u?file=src%2Fapp%2Fhello.component.ts

ngOnInit(){
    this.ls = "dddd"
     setTimeout(function(){ 
      this.name ="helllllll"
     }, 3000);
  }

I am trying to update my name property after 3 sec .but it is not updating.

Why change detection is not working ?

Upvotes: 1

Views: 3215

Answers (3)

Fouad Messaia
Fouad Messaia

Reputation: 171

Use Observable:

// Create observable
const myObservable = new Observable((observer) => {
    setInterval(() => observer.next({ name: 'John Doe', time: new Date().toString() }), 3000);
})

// Subscribe to the observable
myObservable.subscribe((x: any) => {
    this.name = `${x.name}, Time: ${x.time}`;
});

https://stackblitz.com/edit/angular-ce3x4v

Upvotes: 0

Abel Valdez
Abel Valdez

Reputation: 2408

You need to implement the interface OnChanges to get the name reference and do the change in the var name this function its executed after ngInit and ngOnChanges its triggered when you are using @Input() decorator demo

ngOnChanges(changes: any): void {
  this.ls = "dddd"
     setTimeout(() => { 
    this.name = "helllllll"
  }, 3000);

}

Upvotes: 1

matmo
matmo

Reputation: 1379

Because in your callback for setTimeout, this is the Window object, not your component instance. You can fix this by using an arrow function, which binds this to the context in which the function was declared:

ngOnInit(){
   this.ls = "dddd"
   setTimeout(() => { 
      this.name = "helllllll"
   }, 3000);
}

Upvotes: 1

Related Questions