Complete Guide to Angular Life Cycle: Hooks & Components
Angular is one of the most popular and reliable open-source application design frameworks that developers around the world use today in developing sophisticated and efficient web apps. This JavaScript development framework and platform are written in TypeScript and maintained by Google. Angular is best used for creating single-page client applications as well as for data visualization. Angular Life cycle hooks are a special functionality that allows us to “hook into” and run code at a specific lifecycle event of a component or directive.
The angular platform was first launched in 2009 by Google with AngularJS as their pioneer initiative. Since then, the Angular team has been innovating the platform and introducing new versions that make web and mobile application development extensively easy and quick. With these innovations and evolutions, application developers were given the freedom to build apps that can run across different platforms- desktop, web, and mobile. One of the primary changes in the Angular platform is the emergence of components. The Angular components have replaced the AngularJs controllers. Though components replaced the controllers, the previous is not similar to the latter. Instead, Angular components look like AngularJs directives.
In order to run any angular component, it has to go through one cycle of events. This lifecycle of events is called Angular Lifecycle Hooks because it hooks up each data flow of the component. The Angular component lifecycle starts with the initialization of components and ends at the destruction of components. The Angular component lifecycle platform that developers use today for creating a sophisticated and scalable web application is a component-based framework. It includes a collection of well-integrated libraries and a suite of tools that developers can use to create, test, and update codes.
In this article, we are going to talk about the following topics:
- Angular components and their elements
- Angular component life cycle hooks
- Different types of Angular life cycle hooks
Learning more about these topics will help you better understand Angular lifecycle hooks and Angular component lifecycle and how Angular frameworks work. If you want to learn and understand Angular deeper, we suggest that you stick with us until the end of this article.
Table of contents
What Is an Angular Component?
Developers use different analogies to describe Angular components. However, we prefer to use the Lego blocks to finely define components. When you want to create a Lego structure, say for instance a simple house, you will need to pick and use different pieces of blocks. You also need to properly stack them together to achieve the design that you want and to build a well-structured final product. Each of these pieces forms part of the entire structure and is considered as a critical building block of the Lego house you are designing. The absence of any of them or any changes that you make would impact the final product.
A similar scenario is also applicable for Angular components. Just as how block pieces form the Lego house structure we discussed above, the Angular components make up a UI of an Angular application. Components are the building blocks of an application that compose an Angular app, define the different aspects of the UI, and represent a portion of a view. Angular components contain the user interaction logic and data that defines the appearance and behaviour of the view. Each component is consists of styles, an HTML template, and a @Component ( ) decorator. The decorator defines the metadata about the class and the template or view to display. It also provides the component with specific information like:
- CSS Selector. The CSS selector elucidates the way the component is used in a template.
- HTML Template. The HTML template specifies how to render the component and what renders on the page. Though the HTML template looks like a regular HTML code, it is partially different since it contains additional Angular-specific syntax which enables it to communicate and connect with the component class.
- Typescript Class. The Typescript class delineates behaviour and is eventually compiled into JavaScript. It also includes the methods that define the logic for the component and the properties that store data.
- Optional CSS Styles. The optional set of CSS styles defines how the HTML elements of the template appear or look like.
The Architecture of a Typical Angular App
The Angular app architecture is primarily based on the concept of components. It is seen in a form of a tree that is composed of loosely coupled components. It begins with the root component as the parent or top-level component of the hierarchy. Below the root component are the second-level child components, and the third level includes the child components of the second-level child components.
Below is a glimpse of how the components hierarchy looks like for a simple e-Commerce app.
AppComponent
CartComponent
Item
List
CheckoutComponent
Confirmation
Payment
AuthComponent
Login
SignUp
Forgot Password
If you form these details into a tree structure of classification, you will get this figure:
This figure clearly defines the hierarchy of the Angular e-Commerce app’s components. As you can see in the figure above, the root component is the AppComponent. Below the root component are the second-level child components- CartComponent, CheckoutComponent, and AuthComponent. The third-level child components (Item, List, Confirmation, Payment, Login, SignUp, and Forgot Password) are all placed below their respective second-level child components.
Primary Elements of the Angular Components
The Angular components are composed of three primary elements, namely; component metadata, component class, and HTML template. Let us take a closer look at these elements below.
- Component Metadata
The metadata defines the additional data about the component or information for a component used by Angular API in implementing the component. The metadata is also used in processing the class. This extra information includes the component’s HTML and CSS files location, providers, selectors, and more. An @Component decorator is used to provide the needed metadata to the component.
@Component Decorator
An @Component class decorator defines the components. This function adds metadata to class as well as to its methods and properties. Classes with @Component decorator are also treated as a component. The component decorator should always be written with an @ sign at the beginning and should be placed right before the class definition.
- HTML Template
The one that defines the content and layout of the view is the template. It also defines the markups that will be displayed on the user interface like paragraphs and headings. Apart from the content, layout, and markups, the other Angular Components, Angular Directives, and Angular Pipes can also be added to the template. Angular utilizes a two-way traffic system to transfer data between the template and the component. Initially, the Angular Service provides the component with the data for the template. The component then forwards the data to the template. When changes are done on the view, the template will notify the component of such alterations. In order to keep everything between the template and component in sync, you can make use of the data binding techniques like two-way data binding and Event Binding. The template that we are talking about here is closely similar to HTML codes. The only difference is that it comes with Angular Template Syntax which is a special Angular-specific HTML markup. The template can be specified either through providing an external template or by defining the template inline.
- Component Class
The component class is the element that provides the view with the data and logic of the application. It includes the methods that contain the logic and the properties that store data. The component class also contains the JavaScript code that is related to the view or template. Most often, developers use TypeScript in building the component class. However, this does not mean that you are limited to using TypeScript alone since JavaScript can also be directly used in the component class.
Angular Component Life Cycle Hooks
Now that we already have briefly discussed the components and elements of Angular, let us move on to our next topic- the Angular component lifecycle hooks
But before we continue with the Angular lifecycle hooks, let us first take a quick look at what an Angular component lifecycle is.
What Is an Angular Component Lifecycle?
As we have already talked about earlier, components are the main building block for every Angular application. Each of these components has its own lifecycle. During the Angular lifecycle, the components run through eight different phases. Each lifecycle starts from the initialization stage and ends with the destruction phase. What’s interesting is that each of these components is supervised and managed by Angular itself. It is during the initialization stage when Angular creates and presents its root components, produces heirs, and instantiates the component class. Angular then renders both the component and child views. The lifecycle of Angular components continues to evolve from there. Throughout the app development process, Angular will keep checking and evaluating the components for changes and updates in data-bound properties- input properties, data bindings, and expressions. It will also render the projected content. When it detects changes and when needed, Angular also updates the component instance as well as the view. Once a component instance is no longer needed and used, it then enters the death stage which marks the end of the lifecycle. During this time, Angular will decimate such component instance, and then expel its rendered template from the DOM.
What Are Angular Component Life Cycle Hooks?
Angular component life cycle hooks are simple functions that refer to the different events in the life of an Angular component. The life cycle hooks are also regarded as a method that the Angular development platform invokes on the directives and components when a certain event occurs during the component life cycle as it creates, changes, and destroys them in the course of execution. It is also considered as a callback function that the platform raises whenever there are positive events in the life of a component. The term “Angular lifecycle hooks” is likewise used by angular app developers in describing or pointing out specific points or stages in a component’s life, especially during the process of Angular application development. It helps developers modify and polish up the behavior of the app components during the process of creation, update, destruction, and alter Angular component lifecycle. An Angular app can use the lifecycle hooks to check, understand, and evaluate key events in a component’s life. This allows better initialization of new component instances and detection of changes. The Angular hooks also help in tapping events to respond to updates when needed during change detection as well as to clean up before removing the component instances from the DOM.
Different Types of Angular Component Life Cycle Hooks
The Angular component lifecycle has 8 different hooks. These are:
- ngOnChanges
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
- ngOnDestroy
- ngOnChanges
The ngOnChanges life cycle hook is a callback method that is executed whenever there are changes in the input control of the component or when variations on the data-bound property occur. These Angular lifecycle hooks are invoked before ngOnInit and respond when data-bound input properties are set or reset. It receives a changed data map or SimpleChanges object that contains the previous and present position or values of the data-bound property. Note that Angular will only invoke the ngOnChanges Angular life cycle hooks if the component has input. You can use it in all components provided that they have input in them.
- ngOnInit
Angular initializes the ngOnInit Angular lifecycle hook after creating, setting, and introducing the input values or properties of the component. This Angular lifecycle hook is also invoked after ngOnChanges and as Angular displays the data-bound properties. The ngOnInit lifecycle hook initializes data for the component or the logic for the components. Angular CLI adds this hook to Angular components lifecycle by default. Please note that these Angular hooks are only called once. Even without invoking ngOnChanges first, Angular can still invoke ngOnInit. This is true for cases when ngOnChanges can’t be invoked just like when the component has no template-bound inputs. In this case, ngOnInit is called after the constructor.
- ngDoCheck
These Angular lifecycle hooks are invoked during every change detection cycle. It can detect and act upon changes that even Angular fail to detect on its own. The ngDoCheck hook can also be invoked even without any changes in the input properties. It is called right after ngOnChanges and ngOnInit.
- ngAfterContentInit
Just like ngOnInit, ngAfterContentInit Angular lifecycle hooks are also called only once in the entire life of the component. Angular invokes ngAfterContentInit right after the first ngDoCheck. The ngAfterContentInit Angular lifecycle hooks initialize the content. It responds as soon as the external content is projected into the view of the component. It can still be called even without any content to project.
- ngAfterContentChecked
Just like ngAfterContentInit hook, ngAfterContentChecked is summoned after the initialization, checking, and update of the external content. ngAfterContentChecked Angular lifecycle hooks are called after checking the content project into the component or after the view and child views of the component are fully initialized and during every change detection cycle. These Angular lifecycle hooks are invoked after every subsequent ngDoCheck, after ngAfterContentInit, and after every change detection cycle.
- ngAfterViewInit
These Angular lifecycle hooks are also called only once during the first change detection cycle, specifically, after ngAfterContentChecked, and after the initialization of the view and child views of the component.
- ngAfterViewChecked
After Angular completed the checking of the view and child views of the components, it will then invoke the ngAfterViewChecked hook. ngAfterViewChecked is called every subsequent ngAfterContentChecked and after ngAfterViewInit. These Angular lifecycle hooks are only applicable for Angular components.
- ngOnDestroy
As we have mentioned above, the components that are no longer in use end up in the destruction phase. Angular will call for the ngOnDestroy lifecycle hook after it has completely destroyed such components. If you want or need to unsubscribe from all observables, utilize the clean-up logic, or disconnect from any event handlers, this is the best time to do so. Implementing these actions during the duration of the ngOnDestroy Angular lifecycle hooks will greatly help you avoid memory leakage in the future.
Endnote
The lifecycle hooks that we have discussed above are also applicable for Angular directives. Please note that you need to know and understand the basics of TypeScript programming first before you start working with the Angular component lifecycle hooks. Also, you need a basic understanding of the fundamentals of Angular app design as well as the processing steps of the lifecycle of the component. It is critical to know that not all projects need all of these Angular hooks. Your project may not need to use and follow all the eight Angular lifecycle hooks. With that being said, you need to choose the hooks wisely and choose only those necessary and applicable for the type of Angular app you are building. For a smoother process and a successful Angular app development project, you need to ensure that the developers who are working on developing the app that you want know the importance that each component holds in Angular. They must have a better and in-depth understanding of the different Angular lifecycle hooks and the role each hook plays in the lifecycle of Angular app development. If you are looking for a reliable team of angular developers who can help make your dream Angular app who can help make your dream Angular app a reality, choose none other than APPWRK IT SOLUTIONS . We have a dedicated team of Angular experts who have in-depth knowledge and understanding of the ins and outs of Angular app development especially in terms of Angular design, Angular component lifecycle, and Angular lifecycle hooks.
You can hire dedicated angular developers from APPWRK anytime! It is our promise to deliver outstanding quality – at par excellence!
Related Links:
About author
Whether you are planning a start-up or want to enhance your existing business, APPWRK is a one-stop solution to satisfy your goals and expectations. We have action-oriented experience in UI/UX, Mobile, and Web App development. Also, you can knock on our door for Quality Assurance and Digital Marketing services.
Book A Consultation Now!