DEV Community

Cover image for Angular: HTML Events and Asynchronous Handlers
John Peters
John Peters

Posted on • Updated on

Angular: HTML Events and Asynchronous Handlers

//A normal regular synchronous change detection
<input
 // the ngModel traid for 2 way data binding
  #city="ngModel"
  [(ngModel)]="address.city"
  (ngModelChange)=
    "address.city = onPropertyChange(city)"
  onPropertyChange(city) {       
      return city.viewModel;    
   }
/>

Enter fullscreen mode Exit fullscreen mode

Specification changes, we need to kick off asynchronous work. We think, no problem; we'll just make the function async.

  async onPropertyChange(city) {
      //Kick off this async job
      let something = await getSomething();
      return city.viewModel;    
   }

Enter fullscreen mode Exit fullscreen mode

NOPE
Can't do that, Angular throws an error.

Correct Way

 onPropertyChange(city) {
   Promise.All([getSomething]).then(result=>{
        //result here
   });        
   }
  return city.viewModel;    
 }

Enter fullscreen mode Exit fullscreen mode

Contain the async work inside the function!

Top comments (0)