Essential Angular 9 Development Cheat Sheet

Essential Angular 9 Development Cheat Sheet

Angular is a front-end web-development framework and platform that is used to build Single-page web Applications (or SPAs) using TypeScript as the primary programming language. Angular is itself written in TypeScript. Angular is an opinionated framework which means that it specifies a certain style and establishes certain rules that developers need to , learn, follow and adhere to while developing apps with Angular, therefore you need to learn Angular and the various modules, components, tools that are used and that make up an Angular app. 

There are way too many versions of Angular that you hear about and as a beginner, it is likely that may get confused with so many different versions out there for the same framework. There are versions like AngularJS, Angular 2, Angular 4, Angular 5, Angular 6, Angular 7, Angular 8 and now Angular 9 that you may have heard of. Too many versions, right? Well, in reality, there are just two different frameworks – AngularJS and Angular. 

AngularJS was the initial release and was called as AngularJS. It was the JavaScript-based web development framework which was first released in 2010 and is maintained by Google. Later, in September 2016, Angular 2 was announced which was a complete rewrite of the whole framework using TypeScript which is a super-set language of JavaScript. 

Since modern browsersdo not understand TypeScript, a TypeScript compiler or transpiler is required to convert the TypeScript code to regular JavaScript code. 

In this article, we will talk about everything about Angular that you can use as a quick reference guide. We will go through the core concepts, commands, utilities, etc. 

Angular CLI or the command-line interface is a very powerful and sophisticated tool that allows you to perform a lot of actions in an Angular project by using simple commands. From scaffolding a brand-new Angular project to building the project for production, the CLI takes care of everything.  

CLI also allows you to debug the application during development locally using a development server that monitors the source files for changes and when you change any of the files, it automatically recompiles the source code files and refreshes the app in the browser. Pretty neat! 

You can use the CLI tool directly in a command shell, or indirectly through an interactive UI such as Angular Console. 

Let’s have a look at some of the most common ways we use the Angular CLI. 

An Angular app is composed of components. Each component can contain more components which essentially makes an Angular app a tree of components. A component is made up of an HTML template, a typescript class and a stylesheet file. These three pieces together form an Angular component. Each component in Angular has a lifecycle which is managed by Angular itself.  

Angular creates it, renders it, creates and renders it’s children, checks it when it’s data-bound properties change, and destroys it before removing it from the DOM. Angular allows you to hook into significant lifecycle events using hooks. Here are these hooks and their brief significance

Interpolation is a way to use the properties in the component’s TypeScript class within the HTML template. Interpolation has a very simple syntax. Here is an example. 

Consider the following property of string type in the component’s TS class. 

The same value can be used in the HTML template using the following interpolation syntax. 

The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. Interpolation can also be used to concatenate strings, or perform simple mathematical operations right within the template. The evaluated result is rendered on the page. 

An example – 

Another example –  

The same technique can also be used while specifying the values of properties. Here is an example. 

Clearly, using property binding is much readable and recommended syntax if you intend to use the values of component properties in the template. 

Binding in Angular is used to define values of HTML properties and events using class members.  

Here are a few examples of property binding in Angular. 

In the above snippet, the title property is bound to a variable called company_name in the template. The same property needs to exist in the component’s typescript class, otherwise you will get an error. Similarly, you can bind to any properties exposed by HTML. 

Here is another example. 

The placeholder_text property needs to exist in the component’s class. 

You can also bind events to methods in Angular. Most HTML elements have events that they emit when certain conditions are met. Binding methods to these events allow you to perform an action in your code. For example, executing a method on the click of a button is the most common use-case of event binding. Here is a code snippet for the same. 

In the above code snippet, you can see that the click event is bound to a method called sendFOrmData(). Whenever the user clicks on the button, the function will be executed. Keep in mind that the sendFormData() method needs to be a member function inside the TypeScript class of the component otherwise you will run into errors. 

The most popular and powerful feature of Angular is two-way binding. With the help of two-way binding, when data changes in the component, it’s immediately reflected in the template. You need to use the ngModel directive with the special binding syntax to use two-way binding. 

Here is an example. 

Using the above code snippet, if you type in some text in the input field, the value of the username property will change as you type which in turn will update the value in the HTML template as well. All of this happens in real-time. 

Structural Directives 

There are two structural directives in Angular – NgFor and NgIf. 

The ngIf directive is used to add or remove an HTML element from the DOM completely based on a certain condition. The value passed to ngIf should either be a boolean value or should be an expression that evaluates to a boolean value. Here is an example. 

In the above snippet, the showButton property is used to decide if the button will be displayed on the page or not. Do not confuse ngIf with the hidden HTML property. The hidden property only hides the HTML element, which ngIf completely removed it from the DOM. 

Another structural directive is used to render HTML elements on the page based on an array or iterable. Here is an example. 

If you execute the above code snippet, you will see a list rendered out on the page with the data based on the array. If you make changes to the array, the list will be updated automatically. 

Pipes and Services 

Pipes and services are also TypeScript classes just like the component classes. The only difference is the functionality that they offer. They are marked differently by using the decorators. 

This declares that the class is a component and also provides metadata about the component. 

This declares that the class is a pipe and provides metadata about the pipe. Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. They are all available for use in any template. Here is how you would use a pipe in Angular 

This declares that the class contains dependency injectors, this means the data provided by the injector should be injected into the constructor when creating an instance of this class. Basically, this marks the class as a service to be used by other classes. 

To create a pipe, you need to use the following CLI command. 

Similarly, to create a service, you need to execute the following CLI command. 

Angular is all about components that have to interact with one another. Inputs and Outputs are used to allow interaction between two components. Inputs allow a component to receive some data from the parent component and outputs allows the component to send some data outside the component back to the parent component. So inputs and outputs are used to implement parent-child interaction within components.  

Let’s have a look at how we can allow a component to receive an input. The key here is using the @Input decorator. 

The above code snippet is added to the component’s TypeScript class. Now, the component can accept an input called “username” as shown below. 

The value “KnowledgeHut” can now be accessed within the component using the username property. 

The other direction of communication is from child to parent. In this case, the child emits some data using an event. The parent subscribes to this event using event binding and receives the data. Here is an example. 

Inside the child component – 

To emit the event, 

That’s all in the child component. 

Here is how the parent used the child component with outputs. 

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. 

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

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

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

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.  

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

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. 

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

Build the App 

The Angular CLI allows you to build the app.  

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. 

There are a few more flags available. 

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 –  

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 

  • prod 
  • outputPath 
  • localize 
  • aot 
  • baseHref 
  • buildOptimizer 
  • index 
  • verbose 
  • optimization 
  • NgxBootstrap 
  • Angular Material 
  • Ng2-Charts 
  • Ngx-Text-Editor 
  • NgxDataTable 
  • Research & References of Essential Angular 9 Development Cheat Sheet|A&C Accounting And Tax Services
    Source

    Leave a Reply

    Related Post