Change Detection in Angular Pt.2 - The Role of ZoneJS (2023)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome back to my video series on Change  Addiction in angular in this second video   we will take a closer look at song GS library  and its role in change detection process you   will learn about multi-patching technique how  it looks in the practice and how angular uses   zone.js Library under the hood if it is  your first time on my channel my name is   Dmytro Mezhenskyi and here you can find a  lot of advanced and lore tutorials that you   can check out later but now we are getting  started right after this short intro [Music]   foreign if you remember in the previous video I  told that I like to split change detection into   two processes the first one is recursive view  checking and the second process is the one that   triggers The View checking process automatically  also I said that we could disable the second   process using the following config in the main  TS file and triggered the view checking manually   by using the change detector ref associated with a  particular component view for that we have to call   the deck changes method whenever the component  data model changes it makes angular walk through   all bindings in the view and refresh the view  according to the new binding values of course   it might be very inconvenient to trigger view  checking manually so it would be cool if angular   could schedule view checking for us automatically  but before we come to automation part let's   quickly figure out in which cases the state of  our our angular application might change we can   already clearly see that the state can be changed  in some set timeout or it could be maybe some set   interval Global methods right or we could change  the component State when we handle any event like   click Focus Mouse move etc etc or the state can  be changed when the HTTP call is completed and   we received some data from the server so we can  conclude that pretty much every async operation   can potentially change the state of our angular  app so we need some mechanism that will notify   angular that hey some async operation completed  it is a great time to schedule view checking   cycle by calling the detect changes method of  for the root component view right and angular   has such a mechanism enabled by default so if  we revert back stuff in our main TS file and of   course first go and remove the the deck changes  call right here you can see that now changes in   our data model were magically picked up and  the view was properly synchronized and this   magic is possible thanks to Zone GS library but  how exactly does it happen well to notify and   glor about a sync event completion some GS uses  technique called monkey patching to patch the   browser's native API and bring some additional  Behavior some interceptors and hooks to it it   might sound a little bit unclear I understand so  let's learn it by do it and I would suggest take   any JavaScript window method and let's just  monkey patch it and I bet you will grasp the   idea immediately for example let's take one  of the methods from the window object called   console lock everyone knows what is console log  function it is the world first debugging tool   of course I'm joking but yeah let's monkey patch  it so firstly we have to get a reference to the   original console log function so let's do it and  save this reference in some constant then because   JavaScript allows us to override basically  anything Nothing Stops us from overriding the   original console log to some new function that  could do any logic there but we don't want to   completely change the behavior of this new console  log so we're going to call their original console   log inside of course we don't want to log out the  void so we would need to proxy parameters which   contain some strings or object that needs to be  logged out so let's grab all provided parameters   from for the new console log and spread it  in the original one great so now before or   after the original console log call we can add  any additional logic there and it is actually   the monkey patching in action for example we can  warn a developer that you know unlike the regular   console log this one will trigger recursive view  checking and we actually can trigger it by getting   a reference to the application Root component  instance using their corresponding method in   the NG object this is utility object which is  available in the global window object when you   run your angular application in development mode  and since this component has access to change   detector ref we can trigger you checking for the  root app component so now if we try to console   lock anything in our application there will be  called the monkey patched version of console   lock which called the original console log then  it prints a warning and it triggers view checking   for the application Root component and this is is  quite a similar and very very simplified version   of what zone Gs does with Native browsers API  sure it is far from the real implementation   and how it works together with angular but this  mental model hopefully helps you to understand   their general idea in reality the implementation  is a little bit more complex but anyway let's walk   through the key moments there so everything  starts when we bootstrap a model or component   there angular creates the instance of the NG  Zone class one of the responsibilities of this   class is to create a child's Zone exactly for  their angular application and it uses special   interceptors or callbacks for the Zone in order  to bring the connection between angular and this   zone for example on invoke task callback will  be called by Zone in order to execute tasks   like microtask micro tasks or event tasks and  once the task is executed before leaving the   call stack here happens a couple of checks where  one of them checks if there are no pending tasks   to execute and if there are no tasks then it  emits a value to on micro task empty which is a   simple event emitter so the event here means  that some async task was executed the task   queue is empty and it gives a hint to angular  that probably the state of some component in   application might change so we have to do with  that something I hope this part is pretty much   clear so let's move forward and then this NG Zone  class instance is provided as a value for the NG   Zone token in angular dependency injection and  then later it is injected into another service   called NG zone change detection scheduler which  immediately after the initialization starts to   listen to the on micro task empty event emitter  and once we get a notification from the zone   that the task queue is empty we schedule a view  checking cycle for our application we do that by   calling the tick method from the application ref  service and as you know from the previous video   it just go through the array of root views  and calls there the deck changes method that   uh performs the recursive view checking for the  whole application view 3. this means that angular   will visit each view from top to bottom check  each binding in The View Run check hooks for   corresponding components and re-render the view  according to the new values in bindings more about   this view checking process you can always learn  from my previous video and the link I will drop in   the video description right there below and here's  another couple of notes about zonjs that I decided   to record at the last moment the first one is that  many developers think that each event each click   each Mouse move on on the page triggers the change  detection cycle of course it is not entirely true   the event can trigger change detection only if  there are two conditions are fulfilled the first   condition this event has to happen with is in  their angular zone so the event listener needs   to be registered in your angular application right  and the second condition is that this event has   to have some Handler because without Handler  we cannot update anything so the state cannot   change so those two things needs to be fulfilled  otherwise change detection will not be executed   the second note I would like to highlight is  that zone GS cannot say to angular state in which   exactly component has changed and if it changed at  all some GS just tells angular that okay probably   some state in some component changed I don't know  where so that's why please perform you checking   for the whole view tree and it makes angular to  do a necessary job and this issue was kind of   solved by on push change detection strategy and  in the next video we will have a look exactly at   this uh strategy but the real solution will come  with angular signals and once they will be fully   adopted I will make the video that where I will  show how signals will impact that change detection   mechanism if you watched until the end and if  you like how I explain angular Concepts then you   probably would be interested in one of my best  video courses about Advanced angular forms and   take just one minute to see what you can learn  from it in just a few easy sections you will be   guided through most of the template driven and  reactive forms features so you can create two   advanced am interactive forms that will impress  everyone and leave you feel proud of your work   but that's not all the course strongly focuses  on custom form controls implementation so you   will learn a lot about control value accessor  and how it is used by angular under the hood   you will get to build custom form controls like  a rating picker and a simple text editor both   of which support template driven and reactive  forms as well as you know validations and other   form control features of course in addition  you will Master a really complex component in   the third section here I'm talking about a drop  down component that supports option filtering   multi-selection and accessible keyboard navigation  with my step-by-step guidance you will be able to   build this advanced form control very easy already  impressive isn't it but even that is not all in   the reminding course sections you will learn how  to create and go performs dynamically from Json   config and which architecture solution can help  make it scalable and maintainable in the future   in the last section you will learn how to manage  validation errors globally so you can dynamically   render error messages for invalid controls without  generating a ton of boilerplate in your component   templates so enroll right now and let's take  your form building skills to a completely new   level the link to the course and discounts will be  in the video description alright guys thanks for   watching I hope you learned something new from  this video and if so please share it with your   colleagues and friends in your social media or in  your work in chats uh whatever and don't forget   to leave your feedback leave your comments and  don't forget to to subscribe to my social media   profiles there I post different tips and tricks  regarding angular and front-end development   but anyway I wish you productive week ahead  stay safe and see you in the next video foreign
Info
Channel: Decoded Frontend
Views: 17,487
Rating: undefined out of 5
Keywords: change detection in angular, zone js, zone js angular, angular change detection, angular change detection explained, ng zone, monkey patching javascript, angular tutorial 2023, angular, rxjs, typescript, codding, Ui, Decoded frontend
Id: Ys7xdebd66Y
Channel Id: undefined
Length: 13min 3sec (783 seconds)
Published: Tue Apr 18 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.