DEV Community

Cover image for Angular: HTML Events and Asynchronous Handlers
JWP
JWP

Posted on • Edited on

1

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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay