简体   繁体   中英

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 ?

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);
}

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);

}

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

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