Angular LifeCycle Hooks - Explained with Examples

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hi guys this is the mayor back with another video this video I'm gonna be talking about very important angular topic which is lifecycle hooks every angular developer needs to be able to understand how and when to use these lifecycle hooks so in this video I will be explaining you how to write different life cycle methods and be able to use it and why to use these lifecycle hooks let's get started at least explaining you with different practical example these are all the life cycle hook that comes very handy in terms of resolving a lot of issues and bugs when we intend to develop big applications before starting I just wanna let you guys know that I built a course on angular and loop back a month ago and I'm gonna give you $10 coupon for my course in the description of this video it is currently 80 dollar course and I'm gonna give you a $10 coupon just go ahead and my course is labeled hot and new and the rating of my course has been pretty good which is you can see four point six and I've got a lot of good reviews on my course you are going to learn a lot of good topics in angular in terms of best practices and Dewback which is the node.js framework for building the api's and build a complete website from scratch so go ahead and draw this course and utilize the coupon that i've given to you in the description below so I'll start off with ng own changes because this is the first life cycle book that gets executed and all other life cycle gets executed after this so I have created a default project which is angular 8 and I have named it angular hooks and it contains default component which is AB component and this is the output of this project so for ng on changes we need to create a parent-child components because this is where we can utilize this lifecycle hook so what I'm gonna do is I'm going to create a child component so in my terminal I'm using BS code for I'm gonna write n GGC and I'm gonna create components folder and I'm gonna name the child component as child and I'm gonna hit enter so it's gonna create a folder here and it's going to print all these files and it's typescript and the HTML file all right so this is the child component that will be used within the parent component which is AB component so now in the app component I'm gonna open up app component and I'm going to remove this title and I'm going to create a variable and I'm going to name it number which is all type number and I can give it any number okay and let me go to output component or HTML and here I'm just gonna remove all this HTML let me just end it with the div and within this h1 I'm just going to write my app and after this h1 I'm going to create another div and I can actually bind this variable over here but what I'm gonna do is I'm going to use this child component and send the data to this child component and use that within ng on changes lifecycle whoo so what I'm gonna do is rather than actually using this particular where here we'll have public variable for this class I'm going to use assessors that will be responsible for setting and getting the data for this particular variable so first of all I need to encapsulate this particular variable and for that I can just simply write private and after that I can write down differ Gators forget counter and I'm going to write this stored number and for setting it and we're just going to write set L am going to call value and this dot number dot value all right and after that I need to make these variables change its value and for that I'm gonna add different buttons over here but first of all that we're gonna create different functions so this is for increment this dot counter plus plus I can actually directly increment this number by writing this thought number but within this component I'm directly using these getters and setters to actually make any changes to this variables okay that's a good practice so now I'm going to write decrement and I'm going to just it - - all right so uh distort number equals actually so value alright so I'm gonna go and open up the HTML file and inside it I'm just going to use up child this is the child component this is it and I'm going to pass it of value that is going to be received within the child component so the variable that I will be creating in the child component let's say my new number and inside this are double quotes are rather than actually using this variable I can't use it because it is private I can use this public counter which is the get so I can simply write counter over here all right so now this is going to be passed to it so for calling these to increment and decrement functions let me just create two buttons so I'm going to call it click and decrement I'm calling this decrement function and I'm just going to name it subtract and I'm just going to copy this line and I'm going to paste it over here and I'm going to name it increment addition make sure there is no spelling mistakes between this increment and decrement all right and now let's open up that child component and in the component of TS file of this child component I need to receive this particular value so I need to create a variable with this particular name all right so let me open up it and for that let me import an input decorator and that would be responsible for creating a variable over here so I can simply write add input and I can name it my new number and which is of type number okay so this variable is going to receive the value coming from here so for actually checking it if it's coming from here or not let me just bind this variable in the HTML and see if it is getting printed or not so rather than actually using pre tag I'm using h2 and within the double curly braces I'm just going to write my new number okay and now let me run this project and see if the values that are coming from this parent component over here is being reflected to the child component and the changes of that integer value this particular number getting reflected within the child component or Nord so now let me just read or this page there is an error let me go to inspect open up this control and it says that can't bind my new number since it has an unknown property AB child alright so let me save all these files so actually files but not safe so that's why it was giving me an error so you can see if this is the value that is coming from the parent component but we are outputting this particular value in our giant component over here so the printing of our value coming from parent component is being done now let's say that I click on any of this button it's going to decrement or increment this particular variable and once it gets decrement or increment it should pass out to this giant component and it should actually reflect the change within this HTML file so let me just click on subtract and you can see it is subtracting let me just edition so it is adding 1 to this particular value so our communication between two components is working fine so now let's use ng on changes lifecycle hook and see how it works and why we need it so now in this child component I need to actually import few more things so I need to use an on changes simple change and simple changes and these are actually used to contain the previous value current value whenever a new value comes into this component we actually need to or get the values what were the current and previous values for these packages actually use to contain those values so now along with on in it I also to implement on changes okay so it is saying me quick fix let me just write down it myself so ng on changes and I'm going to just write changes simple changes alright so this is the parameter that it's going to receive you can see adder has gone alright I have written it above ng on in it because and you own changes execute before ng on in it and we're going to see if I am a true or not so I'm going to actually first of all let me just make this variable private and make its value accessed from Assessor which is going to be set and get all right so now I'm going to change its name to my number and I'm going to make it private and after this constructor just like I wrote input decorator along with this variable I can use input decorator with set Assessor so I'm going to write input and I can write set my new number which is same as this one because I need to bind this particular setter with that variable used in HTML file so here I'm just going to pass out a number which is OP tightened humble and that this dot my number equals to number okay and I need to get it as well so my new number returned this door my number so now it will work fine as it because this particular value is being coming from here but not from my number because it is private it can't be accessed outside this class all right so now I need to use this ng on changes so whenever any change comes from the parent component this particular lifecycle hook gets triggered so first of all actually using this variable let me first log it and see if something is printed or not something came inside it okay so let me save it and now you can see this has been printed because the first time whenever component gets initialized this hooks gets triggered and after that this hooks gets triggered ng on in it now if I click on addition you can see something came inside is being printed over here so if I click on subtract this is being printed so you can see ng on in it only executed for once but ng on changes execute they do whenever any change comes from the parent component to a variable that is receiving a value using input decorator okay so now let's use this changes variable okay so const and nu number change and i'm going to give it a type simple change okay so changes got my new number okay and I'm using this my new number getter for getting the value and now let me just print out it and log and I'm going to write previous value [Music] engi all changes and the new number change dot previous value okay this is a variable that is built-in within this simple change this is an object and whenever you create a variable with this type we will receive previous value and current value coming from that particular change okay I'm going to copy it and I'm going to change it current value ng own changes let me just remove it and let me just update this particular variable with the current when you rather than the previous value okay so I'm using this setter I can directly change its value directly writing this name but I'm gonna use this setter but this dot my new number equals to new number changes dot current value so let me just print out the current value as well just copying and pasting alright okay so now let's go to browser and you can see it printed out previous value which was undefined because there was no previous value that came inside the child component okay but when we click on any of these values it will print again and now you can see this is the previous value this is the current value and this is how we can actually receive the old values and new values using ng own changes now sometimes you get into a problem that are you are actually using a child component and you are changing its value but ng on in it doesn't get executed and you are doing a lot of logic and initialization and you want it to be executed but what you can do is you can use this lifecycle to actually detect these changes okay so now let me just cooperate and paste it over here and I'm just going to remove previous value from here and previous value from here and inside aide I'm just going to let me just remove it ng on in it value so this dot my new number okay now let's see which lifecycle executes before so let's go and now you can see previous value current value executed before ng on M it for this shows it was executed before ng on in it okay now if I click on addition or subtraction there is no ng on in it it means this has been initialized only once so this lifecycle executes only one time but this execute every time any change come from that parent component and this particular variable that gets changed okay so one thing I want to mention here is that let me just go ahead and create another variable within the app component and [Music] I'm not gonna create setters or gathers for it just to elaborate to guys and I'm going to name it oh man and I'm going to pass this name to my child component just like it so I'm going to name it my number two which I'm gonna create in the child component and I'm going to pass out name which is the variable that I have just created okay so within the child component let me just create my number two and which is of type string okay so I'm gonna use a debugger over here because I want my execution of program to get stopped over here and I'm gonna print out my number to actually snort a number it's just a name it's just a mistake in naming the variable but that's fine so there is an error and to resolve this now to make sure all the files are saved at the reason it is not receiving it because I use this input decorator with this setter so I need to use input decorator with this variable because I've got created setter or getter for this particular variable so I'm going to write input and now it should receive this value and now this debugger should stop the execution now it has been stopped now let hover over changes and see what our variables are coming to it you can see it is receiving my new number and current value is this previous value undefined because there was no previous when you first change is true so it means that this change occurred first time coming from the parent component to this child component and second variable which is mine number two which is boomer and it is also first chain previous value undefined okay so I let it go now let me just click on addition or subtraction and see what value is coming to this changes variable I click on addition now if I hover almost changes you can see there is only one object coming from the parent component R which is being received within this simple changes object so if I open up it you can see there's a previous value there is a current value and first chain is false because this is the second time this variable has been changed the reason second object which is my number two didn't came in this child component is because that variable didn't change it remains same from the parent component its value didn't change so all the variables that are changed no matter if there are thousands of variable within the child component but only two variables gets changed this engine on changes and simple changes object will only be receiving those variables which are being changed so it is good in terms of performance of the app so this is where you can use ng on changes life cycle which is the longest life cycle in order to understand other life cycles are pretty easy to understand so once you get the idea of how to use ng on changes which executes at first from all the life cycles so it's going to be really helpful if you are building large application and making a lot of components communicating with each other using input and output decorators so I hope that you have got the ideas for next ah we have ng on in it you already know it executes after ng own changes and for ng on in it what you need to do is you can actually use this particular drag cycle in order to initialize the variables that needs to be used for other functions being written in that particular component whether it's a child component or parent component or our directive you just need to use ng on in it life cycle in order to actually initialize all the variables no matter if it is input decorator or output occur in a simple variables or arrays or object is use ng on it only for that purpose so now I'm going to talk about ng to check it executes after Indian changes and ng on innate lifecycle so what is the purpose and when to use this particular life cycle so I am going to use the same project and for using do check let me just import the to check and I'm going to implement it over here and also I need to write ng to check alright so what I'm gonna do is I'm gonna go open up apt or component or TS and I'm going to make changes to this particular name variable okay so I'm going to create a function update a value and this dot name equals to ally so I'm making changes to the value of this particular variable and I'm going to create a link a click update value and I'm going to name it update all right so this is the link so when I click on it it's going to call this function it's going to make changes to this particular variable and here let me just add a debugger let me add a debugger over here as well ng to check all right so now let me refresh the page so let me check the changes so these are the two changes these are the same as we analyzed before so three values first change current value there is no previous value which is undefined so I'm just let it execute and here it comes in ng to check I'll let it execute okay and let me go to the console and you can see it has printed previous when you current venue ng on M it all right so now I'm gonna go click on Edition and it has detected this change let me click on changes and by clicking on Edition it only changed this particular variable that's why this particular variable has come inside this particular function ng own changes which is the life cycle okay let it go and ng to check so now you can see a previous value current value have been printed and there is no ng on in it because it executed only when this whole component cord initialized okay when we refresh the page it's going to initialize again so I'm gonna click on update now update link so I'm going to click on it so ng own changes have been like triggered and now it has got the second variable because the second variable which is the name has been changed so my number two this is the previous value of my current value alie so this is coming from obviously it's going to throw an error because we are storing the reference of my new number okay but we are receiving my number and my number does not have this particular variable my new number so it's going to throw an error so we can just ignore that so I'm just gonna go we can see it has thrown an error because previously of undefined because this variable did not have the reference to my new number because we didn't get my new number instead we got my number do okay so in this case this life cycle hook got executed so now let me go back to the code and make some changes and inside it rather than actually using this name I am going to create another variable and I'm going to name it user and I'm going to give it name oh man and inside update value I'm just going to use this towards user dot name equals to ally okay let me just remove it because it's for the object now while just passing the data like name I'm just going to pass this particular object rather than passing this name okay so user it's going to be received over here and it is now being used as my number 2 dot main all right so let me just refresh this page again and now you can see we have got two values let it go let it go and now you can see ng on in it and the previous value current value okay so now I'm gonna click on addition and I've got my new number so it's going to execute let me just go and go now if I click on update you will see it did not stop within this ng on changes so it's quite interesting you might be shocked that earlier when I change the value of name it courts talked like here I just changed the name but now I have changed the value of an object which is being the name of that key which is being stored in an object so nothing any difference so why didn't God stop over here so if I just hover over my number my number do sorry it should actually show me the data which is coming from that parent component which is the user okay so the reason it got stopped over here is because we have a concept of pathway venue and the past by reference so whenever any change gets detected using the passed by reference this ng on changes function or a lifecycle bought get detected okay it won't detect any value that gets changed using the passed by a reference but this particular ng to check will be receiving the change so problem using the debugger let me just use this toward my number two and it's going to print out the value okay so let me just let it go and let me open up the console Edition stopped it should have printed this previous value current value and this particular number and now if I click on update you can see it has printed two three four two because I've just printed my number actually let me print out my number two over here click on Edition printed this oh man previous value current value and if I click on update it only printed name only because it didn't go into this ng own changes because it was passed by reference and this particular lifecycle actually detected it's changed and I printed out this object if I click on update again it's going to print out again okay so if I make any change to this particular variable like let's say if I change if I clone this particular variable and I change its address in the memory just like if I copy over here paste it and I change its alley okay now it's not being passed by reference its values not be changed directly in the same memory location because I am recreating the whole new object and it is going to allocate its own memory in the RAM so it's going to get triggered within this energy on changes so it's up to you how you want to use these life cycles okay I'm just giving you the scenarios and how to use it and when to use it but order the purpose of each and every life cycle okay so now if I click on update you can see it has been stopped and this changes has actually detected because this is the current value which is early this was the previous value which was oh man and the reason it got detected by ng on changes is because I actually reinitialize the whole new user variable with a whole new object so the point here is it's up to you how you want to use each lifecycle and I have given you all the scenarios and all the conditions when you want to use what so I'm gonna talk about ng octal content in it now electrocute only one time after this ng to check gets executed it won't execute the second time until will refresh the whole page okay so I'm gonna do the same project first of all I'm going to make it like it because I don't want to throw an error over here because this logic is for only this variable if I'd make any change to the my number two it's going to detect change its going to get triggered and it's going to come inside over here and this second line it goes to an error because we're not handling any conditions because for my number two so now inside the child component it's pretty simple what I'm going to do is I'm just won't copy the name of it from the list ng after content in it and if you want to import it or implement it it's up to you it's not necessarily to import there are few things like ng on m8 and G on changes to check these are the things that are required to be imported but the lifecycle hooks that I'm gonna writing now are not required to import actually ok so inside 8 I'm just going to Limbo it and I'm just going to print here ok so let me save this file and let's see if it gets executed only once or not so if i refresh the page you can see that it printed out previous value current value so it went over here after that it printed ng on in it so it came on ng on in it and after that it should print ng to check because we are writing it on sequence so it printed over here yay and now if I click on any of these buttons this particular who want actually executes it's just like ng on in it so we went to use this particular lifecycle hood it is actually used when we initialize every variable on the array or object in ng on eminent or we perform every logic in these 3 lifecycle hooks and we want to execute a function or make some calculation only once in the whole component no matter if are any other value is going to get changed or we are doing any two-way data-binding we only want to make some changes only once in whenever this component gets sliced and we'll write down that particular lock logic in this particular lifecycle hook so it's pretty simple it's pretty straight away whenever you need it for executing only once you just need to write inside it or call that function which is performing that particulars logic so now I'm going to talk about ng after content check it gets executed right after ng of the content in it once it gets executed we can actually execute this particular lifecycle hook multiple times after ng do check so let's see and now I'm just going to write mg let me just copy the name and for here and soul dot log this fall executed after I'm just going to copy the name yes so now it's going to gets executed right after this yay and you can see this was executed right after ng on in it so I just need to trigger out ng to check and see if this particular log gets printed in the console again or not so the click on update you can see it was executed and after that it just ignored this particular lifecycle book and this particle lifecycle hook got executed so again if I click it again and again this particular life cycle who gets executed again it's pretty simple in terms of understanding it so when to use it actually we we can actually use this particular lifecycle when we want to perform some action all the variables that are being changed under this ng to check lifecycle hook so every time we make changes in this particular hook and we want to perform few more actions we can actually use this particular lifecycle hook so it it got separated because the first time this lifecycle hook cat needs to get executed so in order to avoid its problem I think angular actually introduced a new life cycle hook that can we can used in order to actually utilize it on the variables or initializations that has been changed in ng do check now let's talk about ng after unit so let's just copy it and I'm going to paste it and I'm going to log this false executed of curve I'm just going to copy its name and let's save it and as usual aren't writing all these lifecycle hooks in sequence you must be known that this hook should be executed after this particular life cycle and this particular life cycle used to get executed every time when we make any change to this particular child component but this ng octave unit is only going to get executed once after this particular life cycle hook so ng after content checked so you can see this is the message that was executed if I click on update you can see it didn't get executed so it's pretty straightforward but one important point that I think I need to address here is that let's say that we have multiple grandchild components we have buried a turban used in the child component okay we are just using the grandchild components passing the data in those giant components so all those child grandchild components needs to get executed or initialized completely before this particular lifecycle hook gets executed let's save all those grandchild components include these lifecycle hooks then all these lifecycle hooks of those grandchild components needs to be executed before this lifecycle hook of this giant component needs to be executed so the president's of grandchild components and all those lifecycle hooks written on those grandchild components is greater then this particular lifecycle hook so this is the important point of this lifecycle hooks hoping you need to understand and remember now let's talk about ng after you checked I'm just going to copy it let's go and paste over here you must have got the idea why we need to use this particular lifecycle hook and how many times it's going to get executed so it's going to get executed of every time after this particular lifecycle hook so this particular life cycle who used to get executed multiple times after it so we need to click on update link and so we need to check if this life cycle hook gets executed or not so I'm just going to pop with this name paste it let me go and it was executed by click on update you can see it has been executed again if I click on update it has been executed again so according to my experience why we should use this particular life cycle hook is because once all the child components grandchild components gets executed all the life cycle routes of grandchild components gets executed this and this particular life cycle hook in lies all the variables that are required and once the child component gets executing and all the variables are initialized you can actually do this particular lifecycle book to proceed further and make calculations again and again whenever we make any change at pass any data to this particular component because it's going to get executed multiple times so this is I think the best reason we can use if you think there are other reasons that we can use this lifecycle book for just write the comment below and let me know what are the other purposes that we can use this hope for now let's talk about the last lifecycle okay angular which is ng ondestroy so let's just copy it and I'm just going to paste it over here so ng own destroy lifecycle hook is used when our component is going to get destroyed it means if the HTML is going to get removed from the Dom so let me just give you an example we can actually use this particular lifecycle hookup and we need to unsubscribe or we need to destroy all the content from the page of that particular component so here we are actually using that particular child component okay and let me just define a boolean variable is visible and I'm just going to call it true and I'm going to switch visibility okay this dot is visible equals to not this dot is visible okay you went when this variable is going to gets paused it's going to be initialized with true when it's going to it's true it's going to be initialized with fall from this one copy this variable they make sure you just save all the file and where we are using this particular component I can simply write ng F and I can simply write each variable okay so let me just copy it component is being destroyed okay so let me save all these files let's go to browser and now you can see that message has not been called a solar component is loading okay so now where I'm going if this function needs to gets called switch visibility I haven't created any button yet so I'm just going to copy this particular button and I'm going to paste it over here and I'm just going to call this particular function show or height okay so let's save it and let's go and if I click on show/hide you can see this message has been printed component has been destroyed you can see over here because we can't see that particular component content on the page if I click on it again you can see all the component has been loaded so all the messages of that component are being shown as well if I click on that particular button again we should see that component is going to get destroyed so if I click on again you can see this message has been printed again so once the component gets destroyed and we need to actually initialized our perform something like perform some calculations or call some service functions before actually destroying the components so we can actually write that particular logic inside it or once our that particular component is going to get destroyed we can actually omit the change to value from within the child component to the parent component we can use event ammeter if you know the output decorator is just like the input decorator we can omit it inside ng ondestroy particular lifecycle whoo so guys I hope that you are going to like this video it was pretty extensive but I try to explain each and every point of all the lifecycle hooks that angular introduced in its framework if you have any question make sure you write down in the comment below and for more tutorials for all the technical tutorials in terms of mobile web development desktop development api's development and database administrator and all the technical stuff make sure you hit the like button subscribe my channel and click on the bell icon for getting all the notifications and again just a reminder for you guys make sure you check out the description and if you like my angular hoo pack course make sure you use that coupon and buy that course and learn more and more and become a full-stack JavaScript developer
Info
Channel: Awais Mirza
Views: 36,177
Rating: 4.8095236 out of 5
Keywords: angular, angular lifecycle, angular lifecycle hooks, angular hooks, ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy, learn angular
Id: 0KWQLFI8mFE
Channel Id: undefined
Length: 50min 6sec (3006 seconds)
Published: Sat Sep 07 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.