Search

Exploring the Various Decorators in Angular

There are several important concepts in Angular, and Decorators are an important concept to learn when you are working with version 2 and above of Angular. Through this post we will learn about decorators, its types and how it is being used in real time applications.  Decorators are an important concept in TypeScript and since Angular uses Typescript widely, decorators become an important part of Angular as well.  What are Decorators? Decorators are functions that are invoked with a prefixed @ symbol, and are immediately followed by a class, method or property. They allow a service, directive or filter to be changed before being used. Basically, a decorator provides configuration metadata that determines how the component, class or a function should be processed, instantiated and used at runtime. Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work. There are various types of in-built decorators. Let’s look at each type of decorator in detail. Types of Decorators: There are four types of decorators and each type further has its own subset of decorators.  Class Decorators  This is the first type of decorator which tells us about a particular class’s intent and helps answer questions like whether the class is a component or a module. There are various Class decorators in Angular, and among them @Component and @NgModule are widely used. Let’s see the structure of class decorators via a code snippet. Explanation: The below code snippet uses @Component, which is a type of class decorator provided by Angular.Property Decorators Property decorators are used to decorate specific properties inside a class. Using a property decorator, we can easily identify why we use any particular property of a class Like @Input (), @Output, @ReadOnly (), @Override () The above code uses @Override decorator before the property name which will invoke the decorator. This is nothing but a function and will override the string property name from “pat” to “test”. Method Decorator  Method decorators, as the name indicates, are used to decorate the method defined inside our class with functionality. A common example of method decorator is @HostListener In the above screen shot @HostListener decorator is used before onHostClick () method. Parameter Decorators Parameter decorators allow us to decorate parameters in our class constructors.  @Inject () is a common and widely used parameter decorator. Using this decorator, we can inject services in Angular classes. Structure of Decorators  In all the code snippets that we have seen so far on decorators, you must have noticed that each of the decorators follows a similar pattern or structure when used in code. Each decorator starts with @ symbol and is added before the class, method, property or passed as a parameter. All are functions having open and close brackets. This helps us understand that it is the function which is used as an in-built decorator. Just like a function can be customized, decorators can also be customized. Based on the requirement in our project, we can create custom decorators and use them accordingly. Custom Decorator  In this section we are going to learn the steps involved in creating custom decorators. As the term custom itself suggests, it is something which we create based on our project need which is not already fulfilled by the in-built Angular decorator. So, whenever we want to add some more features to our class, property of class, or method of class we use custom decorators. Here we are going to create a custom class decorator. Step 1. In an Angular project solution structure, create a classes folder inside the app folder.  Inside the classes folder create a class named sample Demo . Step 2. Once the class is created, you can go ahead and create a folder inside the app folder called decorator and add a file name as class.decorator.ts  Step 3. As we know decorators are functions, so we will create a function named Logging, as follows: ‘target’ is the class on which this decorator is going to be used and as we are going to use this decorator on class sample Demo, we have added export keyword before this function. Step 4. As we are going to use this decorator in the sample demo, let us add the sample demo class with decorator.  If we add this class in our main component and invoke, we will see the output on console as custom decorator SampleDemo How to pass data to a decorator The example explained above is a simple custom decorator where we are logging some messages on the console along with the class name where it is used. But if we want to send messages through the class where we are adding the decorator, then we have to change the implementation of the Function Logging.  Function Logging will accept some arguments and return the message as passed by the decorator on class. When we use the decorators in Angular, we pass in some form of configuration, specific to the decorator. For example, when we use @Component we pass through an object, and with @HostListener we pass through a string as the first argument (the event name, such as 'click') and optionally an array of strings for further variables (such as $event) to be passed through to the decorated method. Uses of Decorators in Real Time Applications Almost all Angular applications use decorator concepts; as decorators are functions that allow a service, directive or filter to be modified prior to its usage. @override, @deprecate, @autobind, @mixin are decorators which are widely used in real time applications. Angular framework has several of these kinds of examples which help to achieve complex features in applications. We know now what Angular decorators are and how they work on class, property, methods and parameters to provide information about metadata. All decorators work on a similar principle. We can apply some changes to the behaviour of the default functionality or we can add some custom tweaks to the code before the decorator can be applied to a class, property or method.  There are different ways to call decorators as these decorators can control start from the class implementation to the property and method implementation within the class. Decorators are great when code needs to be customized to suit the needs of the clients and when in-built functions do not help us with what we need.  Summary  When it comes to Angular decorators, we have several options to inject our codes and logic on different levels of class; as everything in programming revolves around class and its objects. Angular, being a rich framework gives us wide options to handle things in our own way. TypeScript has introduced this concept of decorators and those wishing to implement decorators into their code will benefit from going through TypeScript documents to understand more about actual implementation of decorators and its advanced concepts.  

Exploring the Various Decorators in Angular

9K
Exploring the Various Decorators in Angular

There are several important concepts in Angularand Decorators are an important concept to learn when you are working with version 2 and above of Angular. Through this post we will learn about decoratorsits types and how it is being used in real time applications 

Decorators are an important concept in TypeScript and since Angular uses Typescript widelydecorators become an important part of Angular as well.  

What are Decorators? 

Decorators are functions that are invoked with a prefixed @ symbol, and are immediately followed by a class, method or property. They allow a service, directive or filter to be changed before being used. Basically, a decorator provides configuration metadata that determines how the component, class or a function should be processed, instantiated and used at runtime. 

Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work. 

There are various types of in-built decorators. Let’s look at each type of decorator in detail. 

Types of Decorators: 

There are four types of decorators and each type further has its own subset of decorators.  

Class Decorators  

This is the first type of decorator which tells us about particular class’s intent and helps answer questions like whether the class is a component or module. 

There are various Class decorators in Angular, and among them @Component and @NgModule are widely used. 

Let’s see the structure of class decorators via a code snippet. 

Explanation: 

The below code snippet uses @Component, which is a type of class decorator provided by Angular.

Exploring the Various Decorators in Angular

Property Decorators 

Property decorators are used to decorate specific properties inside a class. Using property decorator, we can easily identify why we use any particular property of a class Like @Input (), @Output@ReadOnly ()@Override () 

Exploring the Various Decorators in Angular

The above code uses @Override decorator before the property name which will invoke the decorator. This is nothing but a function and will override the string property name from “pat” to “test”. 

Method Decorator  

Method decorators, as the name indicates, are used to decorate the method defined inside our class with functionalityA common example of method decorator is @HostListener 

Exploring the Various Decorators in Angular

In the above screen shot @HostListener decorator is used before onHostClick () method. 

Parameter Decorators 

Parameter decorators allow us to decorate parameters in our class constructors @Inject () is common and widely used parameter decorator. Using this decorator, we can inject services in Angular classes. 

Exploring the Various Decorators in Angular
Structure of Decorators  

In all the code snippets that we have seen so far on decorators, you must have noticed that each of the decorators follows a similar pattern or structure when used in codeEach decorator starts with @ symbol and is added before the class, method, property or passed as parameter. All are functions having open and close brackets. This helps us understand that it is the function which is used as an in-built decorator. Just like a function can be customized, decorators can also be customized. 

Based on the requirement in our project, we can create custom decorators and use them accordingly. 

Custom Decorator  

In this section we are going to learn the steps involved in creating custom decorators. 

As the term custom itself suggests, it is something which we create based on our project need which is not already fulfilled by the in-built Angular decorator. So, whenever we want to add some more features to our class, property of class, or method of class we use custom decorators. 

Here we are going to create a custom class decorator. 

  • Step 1. In an Angular project solution structure, create a classes folder inside the app folder Inside the classes folder create a class namesample Demo . 
  • Step 2. Once the class is created, you can go ahead and create a folder inside the app folder called decorator and add a file name as class.decorator.ts  
  • Step 3. As we know decorators are functions, so we will create a function named Logging, as follows: 

Exploring the Various Decorators in Angular

target is the class on which this decorator is going to be used and as we are going to use this decorator on class sample Demowe have added export keyword before this function. 

  • Step 4. As we are going to use this decorator in the sample demolet us add the sample demo class with decorator.  

Exploring the Various Decorators in Angular

If we add this class in our main component and invoke, we will see the output on console as custom decorator SampleDemo 

How to pass data to a decorator 

The example explained above is a simple custom decorator where we are logging some messages on the console along with the class name where it is used. 

But if we want to send messages through the class where we are adding the decorator, then we have to change the implementation of the Function Logging.  

Function Logging will accept some arguments and return the message as passed by the decorator on class. 

When we use the decorators in Angular, we pass in some form of configuration, specific to the decorator. 

For example, when we use @Component we pass through an object, and with @HostListener we pass through a string as the first argument (the event name, such as 'click') and optionally an array of strings for further variables (such as $event) to be passed through to the decorated method. 

Uses of Decorators in Real Time Applications 

Almost all Angular applications use decorator concepts; as decorators are functions that allow a service, directive or filter to be modified prior to its usage. 

@override, @deprecate, @autobind, @mixin are decorators which are widely used in real time applications. Angular framework has several of these kinds of examples which help to achieve complex features in applications. 

We know now what Angular decorators are and how they work on class, property, methods and parameters to provide information about metadata. 

All decorators work on similar principle. We can apply some changes to the behaviour of the default functionality or we can add some custom tweaks to the code before the decorator can be applied to a class, property or method 

There are different ways to call decorators as these decorators can control start from the class implementation to the property and method implementation within the class. 

Decorators are great when code needs to be customized to suit the needs of the clients and when in-built functions do not help us with what we need.  

Summary  

When it comes to Angular decorators, we have several options to inject our codes and logic on different levels of class; as everything in programming revolves around class and its objects. Angular, being a rich framework gives us wide options to handle things in our own way. TypeScript has introduced this concept of decorators and those wishing to implement decorators into their code will benefit from going through TypeScript documents to understand more about actual implementation of decorators and its advanced concepts.  

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

7 Things to Keep in Mind Before Your Next Web Development Interview

Websites are an integral component of any business. According to research by techjury, there are approximately 4.3 billion internet users in the world, which makes the internet the single largest source for an audience. Organizations have identified this factor, and every business today has a website that represents them online. In fact, many companies, like ecommerce stores and food and beverage companies, for example, make their largest profits directly from their website.The requirement for website development, revamping and maintenance makes web developers sought-after candidates for every company. As a web developer, your options are many, and by regularly upskilling yourself, you can ensure a lucrative career. Before you attend your next interview, make sure to go through interview questions and answers online to be prepared. In this article, we cover seven tips for web developers to crack their next interview.1. Learn how to design In most companies, design and development are handled by different teams, and rightly so since they are two different disciplines that require a different skillset. The former is in the creative field, and the latter is technical. However, a candidate who can handle both is always going to be preferred. As a developer, you need to know the basics of design, the rules of UI and UX, and understand brand guidelines. These basic design skills will help you be more involved in the project and be a plus point to crack your next interview.  2. Be proficient in basic languages Every web developer needs to have a strong grasp on the ground level languages: HTML, CSS, PHP and JavaScript. Whether you develop on WordPress or code in Angular, your knowledge on these four languages will be tested. Prepare by going through knowledgebase articles for each of these and looking for interview questions online, especially JavaScript interview questions because a lot of companies look for animations that are triggered through JavaScript. 3. Learn multiple platforms Technology is ever-evolving. Make it a point to stay updated and learn new languages on a regular basis. Many websites and web apps today are built on different platforms: AngularJS, Python, React, Django, etc. Knowing more than just the basic languages will give you an edge over other candidates and pave the way for faster career growth. 4. Learn the basics of editing tools We have already discussed how important it is to add design as a skill to your portfolio. One way to do this would be to learn how to use editing tools such as Photoshop and Illustrator. This will also reduce your dependency on the design team whenever you need basic design edits like resizing or recolouring of images or layouts. Not only will you be able to complete projects faster, but you will also add bonus skills to your resume that interviewers pick up on.  5. Create an online portfolioThe best resume for a web developer is a website! If you can create a visually stunning website that is also agile, you can impress interviewers just by showcasing it. An online portfolio is a great way to show in real-time what you’re capable of, and also to showcase all your previous projects. It also helps potential employers find you online.  6. Be prepared to create a mock website Companies nowadays place a premium on seeing you walk the talk. Rather than asking you a bunch of questions, they give you a single page design and ask you to develop it at the interview. There usually aren’t any restrictions and interviewers let you choose the language and platform (unless the interview is for a specific language). Go into the interview prepared for this scenario by deciding beforehand what your strengths are and what platform you can complete this task on within the fastest time possible.  7. Relax, there are plenty of opportunities We began this article by giving you an idea of how much in demand web developers are. With many start-ups springing up and companies constantly revamping their websites, there are going to be numerous opportunities for you to land a well-paying web developer job. You can also look for freelance projects online on websites like Fiverr. Ace your next web development interview These are some core areas that every web developer needs to be proficient at. With the stiff competition today, mastering just one skill is never enough. Fortunately, there are a plethora of online courses and articles that will help you prepare and bag a career-defining web development job.
6650
7 Things to Keep in Mind Before Your Next Web Deve...

Websites are an integral component of any business... Read More

Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript used pretty much everywhere. For the seventh year in a row, we see it ranking as the most popular and widely used programming language, a good 67.8% of developers having used it in 2019. JavaScript is used to build 95.2% (1.52 billion) websites today, including Facebook and YouTube and some of the most popular and useful apps such as Google Maps and eBay. Let’s take a closer look at what JavaScript is, how and why it was created, and how it seems to be taking over front-end development. It all began in the late 90s when Netscape Navigator, a popular browser was launched by Netscape Communication. In the initial days of Netscape, it was just a software which was able to render static HTMLs, but people wanted it to do more. Netscape envisioned that web pages should be more dynamic in nature. If users are not able to engage with HTMLs, browsers will end up becoming boring pieces of software, they figured.That’s when Brendan Eich came into the picture. He was contracted in 1995 by Netscape Communications to develop a language which would have a low learning curve, so that anyone would be able to write functionalities with it. He developed the language in just 10 days and named it Mocha. A working prototype of Mocha was integrated in the Netscape Browser in May 1995, renaming the language to LiveScript and later in December 1995, it was renamed again, this time as JavaScript. The marketing team at Netscape chose to call it "JavaScript" as Java was extremely popular at that time. With the popularity of Netscape Navigator, Microsoft wished to capture the browser market and developed Internet Explorer with a scripting language named JScript. For a long time, there was no common standard formed for JavaScript, resulting in huge cross browser compatibility issues. Finally, in 1997, Netscape invited ECMA (European Computer Manufacturing Association) to take the responsibility of forming a specification for JavaScript.Since then, the ECMA has released updated specifications for JavaScript regularly and browsers try to follow these specifications in their implementation of JavaScript engine.Fact Check: Today, Brendan Eich is the CEO of Brave Software which builds a privacy oriented, chromium-based browser named Brave.Fact Check: Netscape Navigator later became the foundation stone for Mozilla Firefox. They retained the same name for their JavaScript engine "Spider Monkey" which was part of the Netscape navigator.Need of Framework With the ECMAScript specifications in place, developers began to use JavaScript  to make the HTML page much more dynamic using JavaScript. However, there were still a few developers who preferred to write big client-side functionality with JavaScript, owing to low performance of browser and JavaScript engines. Perhaps, the industry had a more a server-side performance focus in that era. Then, as computers became more powerful, browser performance improved and JavaScript engines evolved, developers started moving client-side logic to browser using JavaScript.Once developers started writing more and more JavaScript, the community felt the need to write logic in a more structured and scalable manner, so as to be more understandable, readable, manageable and less error prone. The need for a framework in JavaScript was clearly felt.Many frameworks like Dojo, Backbone, Ember and AngularJS eventually emerged within their own communities, which tried to solve problems in their unique way. Collectively, this has helped the whole JS community to move forward towards a more scalable and maintainable web application. ReactJS In 2011, Codebase for Facebook Ads was getting bigger. Developers began to face maintenance issues with it and it was getting harder to add new features in an efficient way. That's when Facebook engineer, Jordan Walke, built a prototype for an efficient application UI. This marked the birth of ReactJS, initially called FaxJS. Later, when Instagram was acquired by Facebook, the folks at Instagram wanted to adopt this framework. Pete Hunt and Jordan Walke then improved, decoupled the library and made it open source as ReactJS in 2013. Since then ReactJS has gone through many changes. The latest version of ReactJS in 2020 is currently 16.13. ReactJS follows component-based architecture and encourages developers to think in terms of small, composable components. Interestingly, this methodology is aligned with an efficient approach for solving any problem in life: the first step to solve a big problem is to break it down into multiple smaller sub problems. Once you have a solution for each sub-problem, you can then add it up to get the overall solution. This can be applied to all problems, big or small. ReactJS asks developer to adopt a problem-solving approach like this to build any UI. It must be noted that ReactJS does not aim to solve each and every problem of building a web application. Rather, it has a narrow focus and a limited scope to solve the one core problem of web development around how to efficiently updating the UI/views.When ReactJS was open sourced in the JSConf 2013, the ideas and changes that ReactJS was proposing were not very well received. For instance, although two-way binding was very popular, ReactJS went ahead with one way data flow. In another example, writing HTML inside JS was considered a bad practice, but ReactJS still wanted to use JSX. All these ideas initially attracted a lot of criticism from the web developer community. In time, however, developers started using it and found it easy to build components efficiently. So, ReactJS now solved the one problem around updating views. But what about all the problems in web development? An ecosystem began to emerge to address the other problems along with ReactJS. Libraries like Redux and React-Router came to life, making ReactJS a complete web framework, although this meant that there would be a dependency on multiple libraries. The ease of using ReactJS trumped all the negative points of the framework and this is what continues to make it a very popular library in web development. In 2020, ReactJS has 50K plus stars on Github and is downloaded 6 million times per week. The ReactJS ecosystem continues to grow steadily; React Native recently bought ReactJS to build cross mobile platform apps. Libraries like Gatsby and NextJS encourage developers to use ReactJS on server and provide benefits of server-side rendering without much hassle. ReactJS has also stood out in multiple developer surveys such as the State of JavaScript. Main design concepts in ReactJS Main design concepts in ReactJSDeclarative, composable, reusable componentsReactJS motivates developers to write small components and reuse the same component at multiple places. Re-usability of components greatly speeds up the overall development and results in less amount of code. Less code is always better because it is less prone to errors. ReactJS encourages developers to write composable components which can be wrapped around any other React component to provide special functionality, thus discouraging the writing of components that do too many things. ReactJS always encourages developers to break their problem into smaller problems, solve the smaller problems first and then combine them to present the overall solution. Less functionality in components always leads to less error prone components. ReactJS encourages developers to write clean, readable, and maintainable code. This is why it emphasizes writing declarative components, which make a codebase easier to read and understand by fellow developers.Declarative, composable components looks a lot like HTML in JS. Instead of standard HTML tags, we have React components as tags. This similarity to standard web semantics is what makes JS somewhat familiar to developers starting out. Reactive Updates Writing static HTML is no fun and it can be said that JavaScript was born to bring interactivity to web pages. ReactJS helps developer to add functionalities in components with which the user can interact and see the results. ReactJS allows developers to attach a state to component and whenever the state of components changes, the component efficiently re-renders itself to produce an updated view. Now, the state of the component can be changed by clicking a button, entering text into the input box or any other part of the component triggering an event. The React component listens to these events and acts accordingly. Updating the whole component UI seems like a terrible idea, but ReactJS has implemented this terrible idea wonderfully by doing it efficiently. In-memory DOM representation ReactJS is able to efficiently update views by keeping a DOM representation in memory known as virtual DOM. Upcoming updates always compare the new DOM with an older copy of the DOM and based on the difference, it figures out the actual DOM elements which need to be updated on the UI. Reducing the number of DOM manipulations makes ReactJS faster. What this means is that writing smaller React components will take up less memory to store DOM representations (Virtual DOM) and ultimately, this results in better performance. Features of ReactJS Main features of ReactJSJSX and Why is it needed When ReactJS was released, it was mentioned in documentation that it is recommended to use JSX along with ReactJS. Now, what is JSX? and do i really need another library to use the ReactJS library? So, let us see how a simple ReactJS component looks without JSX: import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); There is no way the above code looks like a declarative component. The truth is JavaScript does not understand HTML or XML like tags. That is why we need someone to do that conversion for us. Here enters JSX, also known as a syntax extension for JavaScript. With JSX, the above Greeting React component will look something like this: import React from "react";  function Greeting({ name }) {    return {`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root")); JSX actually makes ReactJS code more readable and understandable. You can assume this as a templating library which converts HTML looking syntax into ReactJS element JS code by calling createElement(). Virtual DOM ReactJS has made the term, 'VDOM' or virtual DOM very popular in the JavaScript community. Web browsers have provided APIs to interact with DOM to make our web page dynamic. One can dynamically add or remove nodes in the web page by using these APIs. But interacting with these APIs was very slow, as changing node triggers re-layout and re-paint event for sub-tree. Although the entire subtree is re-rendered (diffing stops when an element type has been modified and subtree is freshly rendered), even in case of virtual DOM reconciliation, the advantage that React offers is that the developer is freed from figuring out which part of DOM really requires updates - the diffing and reconciliation algorithm takes care of it.  React has thus provided a way to reduce the number to change in DOM using virtual DOM. The VDOM is a JavaScript object which contains information of DOM sub tree. We can also call this an object representation of DOM. React uses this object to compare subsequent modification and figure out the minimum number of modifications needed to make in browser DOM to get the desired result. ReactJS claims that the wonderful performance of their library is because of the algorithm they use to compare the virtual DOM. React Native React native is another popular library which is used to build cross platform mobile applications using JavaScript. Before ReactJS, Cordova and ionic were some frameworks which were very popular to build mobile applications using JavaScript. However, these applications did not perform very well. React native uses popular component-based concepts of ReactJS and provides a way to build an efficient mobile application. React native converts JS code into native platform code to run in mobile devices. This approach has improved the performance of mobile applications by a great deal in comparison to other frameworks like ionic. With React Native, ReactJS has now become a very popular library to build UI on any platform. ReactJS: Here to stay Over the past decade, the JavaScript community has seen tremendous changes in language within the developer community. It has seen a lot of new ideas and terms surface in the form of libraries. Developers are building and sharing their work with rest of the world quite frequently and every other day, implementations are open sourced on Github. These new ideas and the problem solving approach continues to help the JavaScript ecosystem to evolve and become better. Prior to ReactJS, JQuery was very popular and was the default library for any web project involving DOM manipulation. With AngularJS and other MVC libraries, we were encouraged to think about a problem in terms of Modal, View and Controller. People have always sought to figure out an approach that can solve the problem. And structuring a solution in a scalable manner is not a new challenge either. We have already implemented scalable solutions at server-side, and they are performing quite well. ReactJS now brings the same pattern to the front-end, where the final output is a UI. To implement this, we break the problem into smaller sub-problems and write solutions for them. This is the basic mental model to solve all UI problems and ReactJS focuses on the same. New ideas in the JavaScript community help the community move forward and eventually, the best solutions become part of the standard JS (ECMAScript). ES modules, promises and some lodash utilities are examples of this. When a library moves in the same general direction as the web, it is bound to be used by a large community. Developers will use these solutions until new specifications are finalized and browsers adopting new specifications. Interim, people will use the feature in the form of third party library.So, is ReactJS moving in the right direction? I would say yes. ReactJS is evolving right along the evolving standards of JavaScript. The front-end community is leaning more towards concepts of functional programming rather than object-oriented methodology. In a similar direction, ReactJS continues to move towards a functional programming pattern. ReactJS has introduced hooks in version 16.8, which encourages developer to build more and more functional components instead of class-based components. Hook does not even work with class-based component. Understanding well that it sometimes becomes a hectic task to figure out which library one should choose to handle state management, ContextAPI and useReducer hooks have been introduced, which help in managing state in small applications much better. Today, with the help of ContextAPI and useReducer hooks, you can build an application without using any other library like Redux. This, however, does not mean that you should stop using Redux as it has its own benefits.Component based architecture is also aligned with the standard web components support in browsers, which allow developers to write non-standard HTML tags in code. In short, ReactJS has made the community become familiar with some of the upcoming web standards. For this reason, I feel that conceptually, ReactJS is going to stay with the community for long. Many big companies like Facebook, Microsoft and AirBnB are supporting the direction and concepts of ReactJS, thus adding credibility to the library. With many big brains backing the library, the ReactJS community looks poised for growth. With no perfect solution to all the problems in web development in sight, the best option is to move forward with whatever is available at the moment. In the JavaScript community too, there is an effort to figure out an alternate to ReactJS such as VueJS and Svelte. Perhaps, ReactJS will get replaced by some other library in the future. However, the basic idea of creating smaller, reusable components is here to stay.Whatever framework we learn, it is most important to grasp the basic idea behind the library. It is this idea or design pattern that is going to remain for good. It may appear in front of you in a different form and shape, but the idea will remain forever. 
9959
Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript u... Read More

What Is the Purpose of AJAX in JavaScript.

Asynchronous JavaScript And Xml (AJAX) is the best solution, whenever you want to update your webpages asynchronously by exchanging the data to/from the server . It simply means that without reloading the complete webpage for your application we can update parts of the web application dynamically and asynchronously without sending the request back to the server. AJAX is the combination of XMLHttpRequest Object, JavaScript and HTML DOM (Document Object Model). As we already know, JavaScript allows us to add enhanced functionality and helps web pages to interact with the clients asynchronously. JavaScript mainly runs on the client side, which is known as the browser. Whenever a JavaScript function sends the request asynchronously from the client to the server, the server responds back with the response which is used to update the page. Generally, the response is in XML format, but it may be in JSON also. In simple terms, AJAX means the interaction between client and server.  AJAX enables us to partially update our web applications asynchronously. When the Ajax interaction is complete, JavaScript updates the HTML source of the page. The changes are made immediately without requiring a page refresh. Ajax interactions can be used to validate form entries while the user enters the data using server-side logic, to retrieve data from the server and to dynamically update data on a page. What is AJAX and How it works:- With the help of AJAX, we can create dynamic web pages which allow us to display the changes immediately without the request having to be sent to the server again. AJAX helps to send only the important data/information to server instead of the entire web page which will eliminate the load on the server. This will help in faster processing and loading of the interactive web pages. How Ajax Works – Whenever a user triggers an event on the web page like a button click. HTTPRequest is sent to the server using XMLHTTPRequest object is configured with the request parameter over the network XMLHTTPRequest makes an asynchronous request to the server.  From server side, the object which will be a servlet or an event listener handles the request which has been received from client, like data retrieved from the data base. The response is built with the requested data in the form of XML document. Using the call back function XMLHTTPRequest object receives the data, processes it and updates the HTML DOM to display the page with new data requested by client.  AJAX combines other technologies as it cannot work independently to create dynamic and interactive web pages. Below is the list of technologies which AJAX uses for building the web pages. JavaScript – When an event is triggered it invokes JavaScript function. Ajax interactions are initiated by JavaScript code, and once the interaction is complete, JavaScript updates the HTML source of the page. DOM – Is used to represent the structure of XML and HTML documents. CSS – Used in building the presentation style to display the content. XMLHTTPRequest—Used to perform asynchronous interaction from client to server using JavaScript Object. Advantages of AJAX— AJAX eliminates the need to submit the form for validation. AJAX allows us real-time form validation, as and when the user starts entering the data in the form. AJAX avoids the entire page being reloaded, as it partially updates the webpage. AJAX is based on open standards like HTML, CSS for webpage presentation. Data is sent, retrieved, and stored in XML which is fetched from the server. Data is fetched using XMLHttpRequest object.     Sending Request and Retrieving the Response:-  Instantiating an XMLHTTPRequest using   var req = new XMLHTTPRequest();  Sending the request to the server, we use open() req.open(“GET”,”test.txt”); the file can be of any type .txt or .xml req.open(“POST”, add-emp.php); GET is generally used to send small amounts of data to the server and using POST methods data is sent as part of HTTP request body. When data is sent using GET, data is sent as query URL parameter, whereas in POST data is not visible. Using send() of XMLHTTPRequest(); we can send the request to the server req.send(); Send() accepts optional parameter body which will allow us to specify the request body. Ajax GET and Post Request:- GET is typically used to retrieve the information from the server. The send() returns immediately as the request is asynchronous; hence we must check where the response exists in its life cycle before processing it further. It uses readyState property of XMLHTTPRequest; readyState is simply an integer value which describes the status of HTTP request, whenever onreadystatechange function is called when readyState property changes. Values of readyState: 0 – UNSENT – request is not yet initiated 1 – OPENED – open() successfully established server connection to fulfil the request 2 – HEADER_RECEIVED – Server has received request successfully  3 – LOADING – Processing of request is in progress 4 – DONE – Request is processed and response is ready at the server. readstatechange event is triggered every time the readyState property is changed. The HTTP status code returns status property of the XMLHTTPRequest’s response, most commonly used status code. 200 – OK Server processed request successfully  404 – Server can’t find the page requested. 503 – Server is temporarily unavailable. POST is used to submit form data to the server. Form data can be sent using FormData object or using query string as req.send(key=value1&key=value2&..&keyN=valueN). Whenever we are sending the data as query string, we need to explicitly set the request header using setRequestHeader(); Req.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”); The setrequestHeader() is called just after open() is called and before calling send(); Most commonly used request headers as part of setRequestHeader();  txt/html, text/plain, application/xml, application/json. With the help of form data we can easily construct set of key/value pairs used for representing form fields and their values are sent using XMLHTTPRequest.send().  Ajax Actions:-   Below are the list of actions that happen in AJAX. Client triggers the event, a JavaScript function is invoked and XMLHTTPRequest object is created and configured. Asynchronous call is made to server by XMLHHTPRequest, server returns the response in XML format. Response is processed using callback() of XMLHTTPRequest object and DOM is updated.  Ajax Security:-   Client-side security in AJAX –  Avoid building XML or JSON dynamically, to make XML and JSON use a safe library to keep the attributes and element data safe. Always keep the data which requires encryption at server side by using TLS/SSL. Never use eval() at the client side, always use .txt instead of .html as .txt prevents most of the XSS problems. To prevent injection style issues, always make sure that the data is encoded properly before sending. Poorly written JavaScript code will help hackers and cause security problems. Users can read JavaScript, so ensure that all the crucial business logic takes place on the server, rather than the browser. Move JavaScript that is not needed at load time to the bottom of the page to make the page load faster. Moving the JS to the end of the page will ensure the browser will display what is needed first and load the JavaScript later on. Always use minified JavaScript, as minification reduces the JavaScript size by removing unnecessary characters. Server-side security in AJAX –  Avoid writing serialization code on the server side  Always use CSRF tokens at the server side. Always use framework while using JSON or XML. Specify authentication, authorization, and other data protection either in web.xml or do it programmatically. ConclusionIn this blog we have learnt that using AJAX we can simply exchange the data asynchronously over the network; updating the page dynamically without reloading the entire content. The popularity of AJAX is increasing as it is a scripting language using JavaScript which provides numerous advantages.   AJAX is a collection of robust technologies that are used to develop dynamic web pages.  It helps us in building more responsive pages by transmitting only the required form data to the server.  One of the important objects which AJAX uses is XMLHTTPRequest object from JavaScript which helps in asynchronous communication from client and server.  Using AJAX we can significantly bring down network load and bandwidth usage by requesting only the required data.  Without AJAX, traditional web pages would take a longer time to get the data from the server.  Even if small changes were present in the web page, the entire web page would be reloaded.  AJAX offers the biggest advantage with Form which is the common element in a web page. Using AJAX, the validation is instant, with callback making a quick round trip to and from the server to retrieve and/or save data without posting the entire page back to the server. By not performing a full postback, network utilization is minimized and operations are quicker.  Ajax enabled applications will always be more responsive, faster and more user-friendly; with vastly improved speed, performance and usability. 
9287
What Is the Purpose of AJAX in JavaScript.

Asynchronous JavaScript And Xml (AJAX) is the bes... Read More