## Essential Angular 9 Development Cheat Sheet

### Reactive Forms in Angular

The Reactive approach of form building uses the classes like FormBuilderFormGroupFormControl, Validators, etc. We define the structure of the form using a form builder and then bind each form element to a form control. This approach is different from template-driven forms where we use ngModel directive to bind input fields to corresponding model properties.

Here is how you would define a simple form with two input fields, one for the email and another one for the password.

this.myGroup = new FormGroup({
email: new FormControl('john@doe.com'),
}); 

Next, we need to bind the form and the input fields as shown below.

<form [formGroup]="myGroup">
Email: <input type="email" formControlName="email">
</form> 

This approach allows you to define Validators on individual form controls and on the form as well.

The Angular Router

Angular router is one of the most powerful modules in Angular which allows navigation within an Angular application. It takes care of lazy-loading components as and when required.

Here is an example of how you would define routes for an Angular app using the RouterModule

const routes: Routes = [{
path: '', redirectTo: 'home', pathMatch: 'full'
}, {
path: 'home',  component: HomeComponent
}, {
}, {
path: 'myblogs', component: MyblogsComponent
}, {
path: 'profile/:id', component: ProfileComponent
}, {
path: '**', redirectTo: 'home'
}];
const routing = RouterModule.forRoot(routes); 

In the template, you need to use the RouterOutlet directive to load the component in a placeholder based on the URL. The Angular Router takes care of loading and unloading components in the placeholder RouterOutlet

<router-outlet></router-outlet>

The routerLink directive can be used to navigate to a desired router. It creates a link to a different view based on a route instruction consisting of a route path, required and optional parameters, query parameters, and a fragment.

<arouterLink='/login'>
<a [routerLink]="['/profile', { id: '23u4h2834y' } ]"> 

To navigate to a root route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the ../ prefix.

### Auth Guards

Auth Guards in Angular are the way to prevent unauthorized access to your routes. They work very well in combination with the Angular Router. It secures your routes. Let’s have a look at an example. Consider the following route definition.

const routes: Routes = [{
path: '', redirectTo: 'home', pathMatch: 'full'
}, {
path: 'home',  component: HomeComponent
}, {
}, {
path: 'myblogs', component: MyblogsComponent, canActivate: [AuthGuard]
}, {
path: 'profile/:id', component: ProfileComponent
}, {
path: '**', redirectTo: 'home'
}]; 

As you can see, we have defined a canActivate property on a route and set its values as an array with the AuthGuard as the only element. Basically, you can have multiple auth guards for your routes but for now, we only have one. Here is how you can create the guard.

ng generate guard AuthGurard

This generates a new guard typescript file and it has a function defined inside of it. All you need to do is implement the function and return true or false based on the user’s state. If the guard returns true for the user, the route access if grant, else not.

Here is an example implementation of the function, canActivate

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return new Promise((resolve, reject) => {
// return or resolve with true or false
}
} 

Build the App

The Angular CLI allows you to build the app.

ng build

The above command compiles the project and generates the final build inside the dist folder. You can however customize the build environment using the --prod flag. You can also change the build destination folder using the --outputPath flag. The following command is another simple example.

ng build --prod --outputPath=myBuildFolder

There are a few more flags available.

• prod
• outputPath
• localize
• aot
• baseHref
• buildOptimizer
• index
• verbose
• optimization

## Conclusion

Angular may seem daunting at first but with steady learning and practicing, it becomes easy to understand and implementation of complex concepts seems simple. It offers a lot of tools, utilities and external packages to build amazing applications.

Some of the most common external packages for Angular are -

• NgxBootstrap
• Angular Material
• Ng2-Charts
• Ngx-Text-Editor
• NgxDataTable

Use this cheat sheet to quickly look for help or use it as a reference. Check Angular docs for more info: https://angular.io/docs

### 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

## What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide morefunctionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented theComponent-based Architecture pattern,but for sure they saw its benefits andhelpedpopularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, Final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So we understand that in component based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? Word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionality. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components. Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of componentswill eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusabilitymeans less code and less code will always lead to less maintenance of code base. React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return {Hello ${name}}; } ReactDOM.render(, document.getElementById("root"));Hmmm, But is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers. JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScriptfile. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { }, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. 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")  ); React.createElement is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be usingReact components using JSX in rest of the article. Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (    Decrement  {value}  Decrement    );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above component can be implemented as class based component like below: import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return {Hello \${this.props.name}};  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic. Component and its lifecycle In React JS, class based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.React lifecycleReact lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromProps static method will be invoked. getDerivedStateFromProps takes two argument - props and state and returns an object to update the state or returns null to update nothing. This lifecycle method is used when the state is depends on props. After getDerivedStateFromProps method, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component: constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating: After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component: getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise: componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from https://nodejs.org/en/. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser. Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.  Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (      -   {count}    +      );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.
Rated 4.0/5 based on 15 customer reviews
6712
What Is a React Component? Write Your First React ...

Prior to ReactJS, Popular frameworks like Angular ... Read More

## Overview of Modules in Node.js

Rated 4.0/5 based on 15 customer reviews
6517
Overview of Modules in Node.js

Node.js is an open source server-side runtime envi... Read More