Demystifying Change Detection in Angular - Pankaj Parkar | ng-India 2019

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
and Pankaj is gonna speak on demystifying change detection and angular so yeah so this is Pankaj so in this talk I will be you know giving a very brief view and then thereafter the detailed view about angular change detection so everyone is aware about angular change detection like it is a heart of an angular framework so basically you know without angle change detection nothing can work so you won't be seeing any binding update on the UI so basically we will be you know we will be starting from the very basic and the gradually we will come up and we will see the details of how it works internally okay so you know before starting let me cover a application architecture in general like how applications work in this era so basically what we have on the on the JavaScript side is model or we just call it as a data or sometime we call it as a state depends on in what you know how you are pronouncing it or how you are dealing with it so currently you can see you have a user object and that user object has first name last name and age which is basic basically a user information user data so I want to display this data on the UI so what you will do is like you would create and template so that template will look like some looks something like this so that template will be something that will have a div and it will basically take care of you know binding those model value on to the UI and simply binding has a user name first name using user dot last name and user dot H on the template and thereafter we do some mechanism and we try to replicate that model state on the UI so that's the purpose like the way we are doing inside angular so angular uses something called a change detection but different frameworks and different library uses something else like react uses virtual Dom plus react reconciliation algorithm okay so what happens is like the the mechanism is like as soon as your data updates at the back end at the JavaScript side that model should there we get updated on the Dom so likewise here I updated the age that was 27 now I change it to 28 so automatically it takes care of updating that thing on to the Dom so this is application architectural overall people following and many of many of the frameworks are targeted targeting the same so a little bit about myself so I am working as a technical lead at synergy right now in Pune so I did I have you know one Microsoft award thrice and I did some coke up I I did some open source contribution as well also I am stackoverflow top user having 100k + repetitions and yeah and if you want to follow me or tweet anything about myself so use handle Pankaj Parker okay so let's get back to the topic so what is change detection so likewise I said I will start with basic basic fundamental like you know what it is in general terms and then then we will go into the detail so if you ask me about the change detection what it is so in simple word I can say that it is it synchronizes your model to the view meaning it reflect as soon as you change your model it gets reflected automatically on the template which is ultimately updating the Dom so let's take an example with angular itself simple example this is simple component which has only title property in it which has a value angular and thereafter that template also has a temp that component also has a template and that template has a span which has title property plus one button which is you know on click of the button I am changing the title property so what do you think what will appear on the UI so UI will be pretty simple as soon as the application gets loaded you will see that since title value was angular it will print angular on the UI and below that you will see a button okay which has a change title as in text so as soon as you click on any title what will happen is like user has performed some actions so generally when user perform some action the state of an application gets changed so what we had what we are doing is like we are changing the title value which is ultimately what our model and as soon as as soon as I click on it it changed the value on the UI so you can see that value now value is updated to the change so this is what the change detection is in general okay so you must be thinking like there is something behind the scene that magic is happening and this values are getting updated but no there is no magic the code that is not a magic that is the change detection mechanism which has been written in angular framework okay so let's dig more into it so you must be thinking like the general question when should change detection happen like you know this is very general question so let's figure out that first so I would just say like as soon as any app as soon as an application state changes the change detection will happen okay okay so this is very vague line so let's dig more into it so you will ask like what what can cause a cause a state change so that is a very important question so to answer to that there are three things so I will cover one by one so one is event callback what what I mean by event callback is when you see any software if what you do is you try to interact with it like by clicking by clicking some button it will open some pop-up or it will crack you get a data from the server and likewise so event callback that is nothing but you know user action after user do an action it might make some call to the server so it could be a network call using xhr so that could that could make a change into the state okay and the third one is timer so that you could use set timeout or set interval to keep eye on something and after some time you want to do some stuff so you can have that work inside the callback so after after you know that callback happens there might be a chances that your state could change so by observing these three things don't you see some some of the you know a thing which is very common they are a synchronous so basically what what what I mean to say those function who are a synchronous they are generally tend to change the state okay so let's I am just you know I am just giving an a brief overview so that's why I want to tell you like if you ask me to you know to implement my own change detection system then how would I do that so the possible implementation could be first thing I said like I will be having a network call and thereafter I will be detecting the changes I mean I will call the detects changes method so for now over here just assume that detects changes method will be a method that will be calling a change detection just assume okay so first thing we handle the network call second the timers so this could be said timeout of set interval okay so I will be calling the detects changes method inside its success and the remaining one was event okay and as soon as event any of the event gets called like focus click mouse over mouse enter we should be calling detect changes method and the implementation of detects changes method will simply look like this as I said earlier what is change detection it is a mechanism which reflects your model on to the view and it keep it synchronous with you know model and view as well so simply the implementation will look like if current state of model is not equal to the previous state please update the view as that of simple okay so that is possible implementation but do you think like in bigger application like enterprise level application we generally make an 10 to 15 Ajax call on the simp single page and should be calling the detects changes method so many times no angular must be doing something behind the scenes likewise we see first example we were not calling detects changes method something was happening behind the scenes correct so let's dig more into the eight so I'm just getting back to simple JavaScript example first and we will you know lighter visit the further part so on our left hand side you will see that there is a function which is like it's it has some epicord like function a function b function C and at the end we are calling function C okay and you know how the execution happened like everything will be maintained inside a call stack so at the initial level when this program gets executed main function will call and later at the end we call the C function so C function will get called and since C function is calling B it will be putting up the B cup B thing inside a call stack then a and a is not having any call further to any other function so what what will happen is a a execution will be completed and it will be removed from the stack latter the same happens with B and B will return the control to the C and and you know the main function will stop working this is how the execution of JavaScript works but this is synchronous and the main thing is synchronous works properly but the synchronous is the one of the major thing so let's look at how a synchronous JavaScript execution works the similar code there is a function a and there after I called set timeout and then I have another function and I am calling that B function from at the end so similarly right now I have three things into the picture earlier only I only had a call stack okay so altogether this system is known as event loop okay so let me summarize in two minutes what it is so first block that you can see over here is a call stack which is which was there earlier as well there are now two new blocks like which is one is wave api's and the other one is Q which is task queue okay what is web api's so wave api's is like the methods that have been provided by the browser to execute something like set timeout set interval likewise okay so let's execute this code I called be like at the end be be were called like B is calling to a function okay and later in between said timeout came but set timeout is what it is a Web API so it will be given to the it will not be executed by the call stack it will be directly given to the set timeout as in Web API okay and in said timeout I mentioned the timer two seconds okay so what will happen is Web API is doing his work now it is working aside it will not stop the current synchronous execution so the synchronous execution will keep on going so a call will finish B call will finish and latter as soon as this happens this says that in in in JavaScript world that one peak happened like and or you can say as one ton so after that after that what happens in the event loop is it will check is there anything pending inside the task queue there is nothing so it will the in between what happens wave API said like two-second has been completed so what it will call it will call the callback function say do something and they are after that do something will be placed inside task queue because it is on a synchronous and thereafter another tick happen and then when tick happens like it will try to check inside a task queue and it will try to get try to execute code from there so this can this task queue can be bigger okay so it will call it do something function and the execution will finish so this is how a synchronous programming works so now you are thinking like how I am going back why I am going back and explaining everything so in angularjs there is something called as zone so how many of you heard about zone okay so basically zone is the guy who helps to do perform a change detection and letting angular know like any something about a synchronous event so basically for for change detection mechanism in angular we uses zone I mean it's completely option from angular version 5 but yeah it was there and it is not a part of angular framework keep that one thing in mind like it's not a part of angular framework it's just something else which is helping angular to letting know like some synchronous event has happened so basically what happens is likewise I said earlier in this slide this things will be taken care by Jones yes so what Jones is does is any a synchronous call happens it calls you know as soon as that call gets complete it notifies angular like yeah this call is done if you want to do something please do it okay so that's why that mechanism is called as monkey-patching like what monkey-patching does is you can have you suppose you have one function and you want to introduce a line suppose a logger at the start of the function and the end of the function so to achieve this what we can do is we can just take a reference of a function and then we put something at the start then we execute the older reference and you know at the end we can put the latter loggers the same function I over here so this is similar as that of an and what John does is by monkey patching it calls zone dot after invoke function at each function level so what that does is it in Tim it emits one event which is observable and that if someone is subscribing to it it will get to know like something has happened okay so cool so moving on to next part so this is what this is component simple component nothing else so but what happens is when angular takes this component and generates some code there after these components gets converted into something called as view and that view looks like and data structure like this and that data structure has everything like it would have a binding it would have a view definition we definition will again have a what what are the nodes available inside the template and and you know the information that will be needed for execution of a component so so you know as soon as angular converts the code into a ot it will refer to view not component okay that's why I am just covering this stuff as well so let's go further yeah so let's dig more like this is a detailed part so this is a snippet I took from angular source code so let's take a simple example likewise what we had before a simple title that is binding on the view so what happens is when a whole application gets started at the time of starting it creates a application rate which is kind of root scope of application this is not totally root scope but I would say a global scope I per application it is also called as platform and what that platform has is it has a reference to each component that is again considered as a views and then directives how many directives is has and what what zone is it it is referring to and everything okay and as I said as soon as any a synchronous task gets complete zone intimates something so what zone says is like it says on micros task MT subscriber will the the observable will emit some value that's why inside angular jangle er framework code you will see that I have subscribed something on on micro micro tasks empty so is it clear okay and thereafter it called next method everyone knows like observable need next and inside our next you will see that when you know when application context created it also creates one zone for that particular application and I am and angular is saying like for this zone run a tick method ok so we will look into that what is 3 method and what it is doing so this stick method is also there inside application application underscore ape dot PS and I also attach the source code line number and the link over over here ok so you can refer that later so what is stick method as I said application ref has access to all the views and directives and other other other metadata that is that ties therefore whole application it loops over each views and fire detect changes method likewise I said so what happens is it goes to the top and the top of the tree it fires change detection for each view so that is what you can see over here this dot underscore views for each for each view called detect changes method okay and for next line if you I mean you must have got an error like what is that error check after value has been changed yeah so that error is because that only comes in development mode and the reason being angular you know particularly chicks like does the binding that have been updated is stable or not because that was a problem that resides in angular JS and that's why angularjs has pin TTL I mean if tained I attained either cycle runs it will be failing like so to ensure that that situation never happens again it says that if it is in Deo mode this is a demo mode flag so again run a change detection for in inside a debut mode so that's why you you used to be getting like that error and you disable the prod mode you will see that you won't be getting an error but your model and the actual value that is displaying on the UI that will not be in a sink okay so let's dig more into it so what are the different change detection strategy that are available in angular JS angular application so one is default and the second is options on push okay so here is a simple componentry of an application assume that this is the application and i have just drawn the componentry okay so there is one root root of application which is the root component and thereafter there is a tree and CD stands for change detector so basically when when each view gets created it has its own change detector because what because it whoa it's supposed to fire a detect changes method on its view that's why okay and other methods are also also there so we will look into that later so what happens is when any change detection fire at this component on the right hand side what happens is it calls a tick method so as I said like any change it takes fire it calls a tick method tick method refers to a root scope or global scope of the of the application so that is why it will first refer to what first view and thereafter it will fire the change detection from for each view from top to bottom okay so so far so clear okay so for this I created a simple demo let me show you that as well wait a minute so this is very simple application which is which is having post in it okay so this is the post is nothing but a post list component inside post list component I have three post one two and three so the the inner boundary is post component this black boundary and then that post component has comments list each post has some comments so this comments list is another component which is another black boundary so when i refresh this page you will see that they all are blinking so what that what that blink says is it is firing a change detection so for that I what I did is I just placed some I am just manipulating a CSS of that particular block by hooking up on ng after Buick okay that lifecycle hook so that's why you say you see like whenever I am changing anything at any of the any of the things like you see I'm changing the text ad at the input and it is firing the change detection for every component so do you think like this kind of situation should happen in big application if you have hundreds or thousands of component then yeah it shouldn't be so that's the next thing like so we are busy we will be needing something more which will which will be you know granular which will be focusing on something which we want to replicate our state on to a particular component so let's take an example of same component tree but only the thing is I just changed the initial first level component on on put strategy okay and thereafter you can see that on those two components that component is expecting name one input and that name one input can be provided by attribute name and name one okay similarly for other other component it has input name too and you can pass on using name attribute and what where that state has been maintained that has been maintained inside a parent component so what is that name one Robbie and name two Pankaj okay so initially the change detection fire will be fire for everyone because on initial run it files for everything so that after some changes has happened and on this component and thereafter it changes a state to name one become as is like but name two changes to Keerthi so what should happen like should it fire a change addiction for both no so basically what what this says is the on push strategy whatever inputs you are passing if that input got changed then only for the change detection for that component and its descendant otherwise don't fire the change detection okay so in this case I have used primitives so which are you know which will be changing each time whenever you change the value because their effort to different reference at each time but with object you will face some problem like if suppose I pass user object over here and I try to modify the user property like first name or last name the on push a component will not let run the change detection because you know you haven't changed the actual reference of an object you just change the property of it so for such cases either you should you know you should do and create a new object or you could use immutable J's for creating a new object each time if any of the property changes so for this also I have a demo so initially what I did is I change this to component not to component thus first the last component comments least comment least comment list too on push strategy using on pull strategy and how on put strategy looks like is let me tell you that as well wait a minute I will share this code as well after the demo after the yeah see the way to mention the change detection is just add one more parameter inside a component metadata and say that it is on push ok sorry Pankaj can you please zoom in zoom in a bit okay sorry is it fine now is it look good okay cool so see this is the way like you can have a change diction option and you can mention on push strategy over here so the demo is like I change comments component to be on on push strategy so let's see again I am refreshing the page so on refreshing on refreshing the page you will see that change detection will fire for all component because it was initial run and later I try to change the input of a particular component you will see that it will fire the change detection for only this comments component not all other component notice one thing I only change change detection strategy for comment Lee is not for post okay so that is why you will see that post is blinking and this comment section is blinking but this comment section and this comment section is not blinking okay okay so moving on to the next part where I did converted all of the component to use on push strategy so this is very interesting thing and this generally happens with enterprise world application so that use case I also covered okay so one here I converted all of the component to use on push strategy okay so I am changing this thing but you will see that it is firing change detection for post component even though it is on on push strategy it is okay like it is behaving for better for the comment section but not for the post section so why this thing is happening so this is happening because of this is how change detection works so what happens is when parent when we run a change detection it goes by hierarchy from parent to child and when it is running a change detection on a parent component what first thing it does is it it calls the update in cool by input binding it it updates the input by input binding of the child component first okay later it engi on in it ng do check and ng on changes events of lifecycle hooks of child component and thereafter it updates the Dom of parent component and then it's run a change detection of child component and then it called after view check and after view in it so I am using after view check method so basically in regards of what strategy you are using angular follows this so that's why you will see that in this case ng after view checked is getting fire but but you know what will happen if you have on push to the descendant component it will it will prohibit it it will only fire for the first level of on push and the next level will be not not be reached out by the change detection system okay so there are other option as well for for making change detection ref better so we already know that we we already called a detect changes method like angular internally does that but can we call it manually yes we can call it so better so let me tell you one thing inside this demo the problem was with this demo is you you are seeing the operations are working fine but not this one sorry this one you will see that everything working fine but for working that making it working I had to make some changes so that change is a minute so inside a post list component it was also on on push and it wasn't accepting any input from the parent so what was happening because it wasn't expecting any input from the parent it wasn't running a change detection for it so I have to explicitly fire a change detection for that component okay so what the difference between tick method and detects changes method is tick method fire change detection from top detects changes method and detects changes method fires change detection from the component that you are calling the detects changes method to its recent descendant and there is one more method that exists is called as mark for check so what does mark for check method says is if you want to run a change detection for a particular path that you want to evaluate a binding so you will you will say that map for say you can call a mark for check method so but basically what it does is from from whatever component you want to call it change detection likewise over here you can take an example of this tree suppose the change detection you want to fire for this component only so you can call a mark for check method for this component what it does is it will traverse a path backward to the root this means like from here to here here to here and while traveling that path it records that path ok and once it recorded for next turn for next change detection run it will for it will run the change detection for that path even though there are you know like there are no possibility of running it like me we are doing it forcefully basically ok so that was it for mark for check and the last is two methods which is which is detach and retouch so basically there could be a cases where in your application you have a widget suppose live score you want to display cricket live score on your application somewhere at the end of your long component tea tree so what you can do is for that case you would be using either set timeout or any I say other as a synchronous function so as soon as you firing a set timeout the NZ zone will say like fire a change addiction for this and if that timeout is 50 milliseconds or less than that you will end up firing change detection multiple times so what you can do is you can detach that particular component from change detection system for a while okay and when you say when you think like I should be running a change detection so either you can call mark for check method or you can reattach that component tree back to the pool component tree so this will this will you know gain a big performance benefit at the time you know at the time of such cases so these are the four method that can make your change detection system very performant and a very you know fast working yeah so yeah so that was it about the change detection and I hope you have enjoyed the talk and you will be you know using this functions at your workplace yeah thank you thank you so much Pankaj for a nice session if you have any questions we have a couple of mics Vic yes sure okay my question is how you will share this PPD's and so I will tweet it and I will I mean the videos are going to post as well so in twitter on twitter you can follow me i will tweet it after this session i mean after some time yeah so code is also there inside a reference section at the last slide so yeah so you can follow me on the twitter handle Pankaj Parker so just mentioned and we can take only two questions sorry to limit we can take questions I guess okay you can you can ask yeah hi okay so what the best way to implement that I mean first you have to decide after what time you have to autosave it like people generally do prefer to have a 300 millisecond or maybe one second so first you have to decide like how much time after how much time you have to do or the select and you can create your own directive and have this this events I mean we can check on creating the form change okay so I mean I mean have you faced any problem while creating this or you want me initial opinion how to build this initial loop okay so basically what I would suggest is obviously you are going to bind it on some form so I would I would think of creating some component or a directive which can accept some observable and who can see it on form tag the form tag which is which it's supposed to save a data and inside that that directive could accept a save function and my directive will have the functionality that that could be overall architectural or architecture of that like I can I can have a detailed discussion on that with you in online yeah thank you
Info
Channel: Geek 97
Views: 7,516
Rating: 4.798995 out of 5
Keywords: Angular, ngIndia, geek97, javascript, ngconf, ngconference, change detection
Id: XTNL4WJRCrM
Channel Id: undefined
Length: 34min 37sec (2077 seconds)
Published: Fri Mar 01 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.