Hi everybody,
During the Angular project implementation, I learned about Lifecycle hooks, so I decided to create this article for everyone to discuss.
The article is referenced from the source (English article): See here
Ok, let’s get started !!!!
Every component or directive in Angular goes through something called Lifecycle hooks , which is called life cycle . People also have a developmental life cycle: birth, growth, aging and death.
So what about in Angular ? There are components in that life cycle, why we need to use and use it in any case ???
By default, Angular has provided us with 8 interfaces as shown above, our job is to implement them through some of the following examples.
- Sample Project
- Understand lifecycle methods order
- Lifecycle methods With Some Examples
- Summary
- Conclusion
Sample project
Below is a sample project of Lifecycle hook, you can download and test it:
1 2 3 4 | git clone https://github.com/bbachi/angular-lifecycle-hooks.git// install dependencies npm install// start the project npm start |
This is the Todo list app that allows you to add, delete, and edit jobs. Through this simple example you will return to Lifecycle hooks .
Understand lifecycle methods order
We will begin to understand the order in which these methods work, when and why they are used.
Here, we add the blue header and footer components to the App components’ view. After that, put all the methods into the component footer, in the header we have a Toggle Footer button used to test the ngOnDestroy () method.
Without any input to component
Start testing the footer part without the @Input decorator and click Toggle footer to test the ngOnDestroy () method .
Results without @Input decorator in component
With the input to component
Ok, got it Now test with the @Input footerText in the footer component to see the change in the life cycle order. Notice that this time ngOnChanges () will be called before ngOnInit () .
… and the result is here
General diagram of the order of methods in Angular
Ok, part 1 of the article should be here. Let’s wait until the next article.