Search

Essential Angular 9 Development Cheat Sheet

Introduction to Angular 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. The Angular CLI 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. ng helpGives you options to get help about any command ot utility.ng versionPrints the version info of the currently installed CLI.ng new <name>  Generates a new Angular project with the provided name.ng serveSpins up the local development server and launches the web app locally in the browser. The command takes more parameters like port and open. The server automatically rebuilds the app and reloads the page when you change any of the source files.ng buildComplies and builds the Angular app into a directory that can be deployed on the web server.ng generateUsed to generate modules, services, components, classes, providers, pipes, etc.Angular Component Lifecycle 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 significancengOnChangesThis hook is executed before the content is processed or child views are loaded. It is also executed when the input properties of the component change.ngOnInitThis hook is used to initialize data in a component. It is called after input values are set and the component is initialized and it is executed only once.ngDoCheckThis hook is called when any change detection runs are made.ngAfterContentInitThis hook is called after ngOnInit when the component's or directive's content has been initialized.ngAfterContentCheckedThis hook is called every time the ngDoCheck is called.ngAfterViewInitThis hook is called after Angular initializes component’s and child components’ content.ngAfterViewCheckedThis hook is after every check of the component's views and child views.ngOnDestroyThis hook is called once right before the component is destroyed. This can be used to clean up memory and release allotted resources and subscriptions.Interpolation 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. company_name: string = "KnowledgeHut" The same value can be used in the HTML template using the following interpolation syntax. {{ company_name }} 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 - name: string = "KnowledgeHut";  age: number = 25; {{ name + " is " + age + " years old today!" }} Another example -  number1: number = 22;  number2: number = 23;  {{ "Sum of "  + number1 + " and " + number2 + " is " + (number1 + number2) }} The same technique can also be used while specifying the values of properties. Here is an example. <div title="Hello {{company_name}}"> Clearly, using property binding is much readable and recommended syntax if you intend to use the values of component properties in the template. Bindings in Angular 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. <div [title]="company_name"> 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. <input type="text" [placeholder]="placeholder_text"> 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. <button type="submit" (click)="sendFormData()"> 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. <input type="text" [(ngModel)]="username">  The name you entered is {{ username }}! 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. <button type="submit" (click)="sendFormData()" *ngIf="showButton"> 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. users: any[] = [{  "name": "Bob"  }, {  "name": "Alice"  }, {  "name": "Tabor"  }, {  "name": "Mock"  }];  <li *ngFor="let user of users">   {{ user.name }}  </li> 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. @Component({...})  class AppComponent() { } This declares that the class is a component and also provides metadata about the component. @Pipe({...})  class MyPipe() { } 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 number1: number = 12.927;  {{ number1 | number:"1.2-2"}} // prints 12.93  @Injectable()  class MyService() { } 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. ng generate pipe <pipe name> Similarly, to create a service, you need to execute the following CLI command. ng generate service <service name> Component Inputs and Output 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. @Input() username: string; The above code snippet is added to the component’s TypeScript class. Now, the component can accept an input called “username” as shown below. <my-component username="KnowledgeHut"></my-component> 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 - @Output() onUsernameChange = new EventEmitter<string>(); To emit the event, this.onUsernameChange.emit("KnowledgeHut"); That’s all in the child component. Here is how the parent used the child component with outputs. <app-child (onUsernameChange)="getChangedUsername($event)"></app-child> Reactive Forms in Angular The Reactive approach of form building uses the classes like FormBuilder, FormGroup, FormControl, 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'),  password: new FormControl('')  }); Next, we need to bind the form and the input fields as shown below. <form [formGroup]="myGroup">    Email: <input type="email" formControlName="email">    Password: <input type="password" formControlName="password">  </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: 'login', component: LoginComponent  }, {  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: 'login', component: LoginComponent  }, {  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 

Essential Angular 9 Development Cheat Sheet

7K
Essential Angular 9 Development Cheat Sheet

Introduction to Angular 

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. 

The Angular CLI 

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. 

ng helpGives you options to get help about any command ot utility.
ng versionPrints the version info of the currently installed CLI.
ng new <name>  Generates a new Angular project with the provided name.
ng serveSpins up the local development server and launches the web app locally in the browser. The command takes more parameters like port and open. The server automatically rebuilds the app and reloads the page when you change any of the source files.
ng buildComplies and builds the Angular app into a directory that can be deployed on the web server.
ng generateUsed to generate modules, services, components, classes, providers, pipes, etc.

Angular Component Lifecycle 

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

ngOnChangesThis hook is executed before the content is processed or child views are loaded. It is also executed when the input properties of the component change.
ngOnInitThis hook is used to initialize data in a component. It is called after input values are set and the component is initialized and it is executed only once.
ngDoCheckThis hook is called when any change detection runs are made.
ngAfterContentInitThis hook is called after ngOnInit when the component's or directive's content has been initialized.
ngAfterContentCheckedThis hook is called every time the ngDoCheck is called.
ngAfterViewInitThis hook is called after Angular initializes component’s and child components’ content.
ngAfterViewCheckedThis hook is after every check of the component's views and child views.
ngOnDestroyThis hook is called once right before the component is destroyed. This can be used to clean up memory and release allotted resources and subscriptions.

Interpolation 

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. 

company_name: string = "KnowledgeHut" 

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

{{ company_name }} 

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 - 

name: string = "KnowledgeHut"; 
age: number = 25; 
{{ name + " is " + age + " years old today!" }} 

Another example -  

number1: number = 22; 
number2: number = 23; 
{{ "Sum of "  + number1 + " and " + number2 + " is " + (number1 + number2) }} 

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

<div title="Hello {{company_name}}"> 

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

Bindings in Angular 

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. 

<div [title]="company_name"> 

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. 

<input type="text" [placeholder]="placeholder_text"> 

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. 

<button type="submit" (click)="sendFormData()"> 

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. 

<input type="text" [(ngModel)]="username"> 
The name you entered is {{ username }}! 

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. 

<button type="submit" (click)="sendFormData()" *ngIf="showButton"> 

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. 

users: any[] = [{ 
"name": "Bob" 
}, { 
"name": "Alice" 
}, { 
"name": "Tabor" 
}, { 
"name": "Mock" 
}]; 
<li *ngFor="let user of users">  
{{ user.name }} 
</li> 

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. 

@Component({...}) 
class AppComponent() { } 

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

@Pipe({...}) 
class MyPipe() { } 

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 

number1: number = 12.927; 
{{ number1 | number:"1.2-2"}} // prints 12.93 
@Injectable() 
class MyService() { } 

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. 

ng generate pipe <pipe name> 

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

ng generate service <service name> 

Component Inputs and Output 

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. 

@Input() username: string; 

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

<my-component username="KnowledgeHut"></my-component> 

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 - 

@Output(onUsernameChange = new EventEmitter<string>(); 

To emit the event, 

this.onUsernameChange.emit("KnowledgeHut"); 

That’s all in the child component. 

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

<app-child (onUsernameChange)="getChangedUsername($event)"></app-child> 

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'), 
password: new FormControl('') 
}); 

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

<form [formGroup]="myGroup"> 
  Email: <input type="email" formControlName="email"> 
  Password: <input type="password" formControlName="password"> 
</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: 'login', component: LoginComponent 
}, { 
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: 'login', component: LoginComponent 
}, { 
path: 'myblogs', component: MyblogsComponentcanActivate: [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

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

How to Install Angular on Windows

In this article, you will learn how you can install Angular CLI on your Windows machine and use it to create real-life Angular Applications/Projects.As you know, Angular is popularly used to create SPAs (Single page applications). Angular is an in-demand, open-source, and modern web application development framework by Google, as compared to all other Libraries and Frameworks like ReactJs, VueJs, MithrilJs, etc.The reasons behind this are many. Angular provides you full access to use all its sub-packages like routing, Async calls, Security, etc.Introduction — What  you will learnIn this blog, we will cover the installation of Angular on Windows. By end of the article, you will understand how to -Install Node/npm on your machine.Use and install Angular CLI globally.Run Angular CLI commands.Create an initial workspace for the application.Run the Angular application in Browser.We assume you are already aware of the basics of web development including HTML, CSS, and JavaScript. (if so, please proceed otherwise we strongly recommand to learn those first before jumping into Angular).In order to continue, you must have — Windows MachineGood Internet ConnectivityWindows user account with all/admin installation privileges where you can install any packages freely.PS: While working with Angular, knowledge of TypeScript is good to have, but is not mandatory. A brief note about Node.jsThe very first thing required to install is Node.js. (If already installed, skip this part and jump to the next part of this blog.)Node.js is again an open-source and cross-platform JavaScript run-time environment that allows to execute JavaScript code outside of a browser (on the Server-side). Node.js is responsible to manage and install all npm dependencies for your Angular application. It provides the required libraries to run the Angular project. Node.js acts as a run-time environment for any Angular application which uses servers over localhost. For more information on Node.js refer to official docs.Angular requires the latest/stable version of Node.js in order to continue. Go to the official website in order to install Node.js on your machine locally.You can install any version, the current one or latest stable version, as per your need. Just click on the button and it will start downloading the package on your machine. Once downloaded click on the icons downloaded and follow the steps, till the installation is completed. To check the version installed of Node.js you can use the following command in a terminal/console window. —node -vornode — — versionNeed for NPM for Angular development As Node.js serves as Run time environment for the application, similarly NPM(node package manager) is used as a dependency management tool for any JavaScript application. NPM will allow us to install the libraries required for any Angular application; for example jQuery, angular-router, angular-http, bootstrap, and many more. You can explore a number of packages available in the npm store here.Note: Once you have installed Node.js it will automatically install NPM on your machine, and you can check the version installed using the below command. npm -vAngular CLI — What it is and complete Installation guideEarlier in the initial days of Angular, developers used to create whole architecture, webpack files, build process, etc for any project on their own from scratch which was quite a time-consuming and lengthy process. To make it easier for the developer, Angular team come up with the easy-to-use tool named Angular CLI. As the name suggests CLI (command line interface) provides a user (developer) friendly interface where you can run commands to make your development life easier and faster. Angular CLI comes with a number of commands available to use from creating a new project, to creating components, creating a routing configuration file, services, and many more.Installation Process of Angular CLITo install the Angular CLI on your machine, open the terminal window and run the following command: npm install -g @angular/cli where -g denotes that CLI is being installed globally to your machine, which means you can create or run any command of CLI anywhere on your machine. Once you run the above command CLI will be installed on your machine, and you can verify the version installed using the following command: ng version To know more about Angular CLI commands, you can refer to this blog which contains a number of commands to use. Creating a Project using Angular CLINow, let’s create our first ever Angular project using Angular CLI. Open your terminal window and type the command below on your machine.ng new hello-world Here ng is our CLI prefix, new denotes that we are creating a new project and hello-world is our project name. You can choose any name you want.After running this command you will find the full architecture of the project in the directory where you run this command. The project folder will be something like below in the image -Angular Project architecture The first file to render on running this application will be index.html which present in the src folder. src folder contains Source files for the root-level application project. assets folder contains all the static assets like images, fonts, etc. node_modules This folder is created while you run npm installby package manager (npm) and it contains all the project dependencies or any third party modules required for the project.  e2e folder contains all the source code related to Test Cases.You can customise it as per your requirements. README.md file is being used as documentation for the app. Package.json configures npm dependencies which are available for the project in the workspace along with their versions specified.  For more details about components/Service and source code you can explore this link. Run the application  one with the installation process of Angular application via CLI, it’s time to run the application locally. Angular CLI comes with complete tool-chain/commands for the development of front-end applications on your machine.Run the following command on the terminal (Navigate to the project directory if you are not in that directory).ng serve or ng serve --open The --open (or just -o) option automatically opens your browser to http://localhost:4200/. ng servecommand will serve your application on localhost server which you can check by navigating to your browser with the below URL http://localhost:4200/. You can customise the port as per your requirement. Accessing Angular Web Interfaceng serve command may take a few seconds to run your application, and once completed, you should see a web page similar to the following. And we are done!Now you can make changes in the default component’s template which is app.component.html .Also, moving forward, you can generate a number of components/service/routing files using CLI commands as per your requirements and keep learning.ConclusionIn this blog you have learnt - What is Node/NPM and how you can install and use it,  What is Angular CLI and how you can use it after installing it on your Windows machine, How to create a new Angular project from scratch using CLI commands and run it. Now that you have basic hands-on knowledge of getting started with an Angular application, you can start exploring Angular further. If you have any questions/doubts related to this blog, please let us know in the comment box below...we would be more than happy to help you out!  
9555
How to Install Angular on Windows

In this article, you will learn how you can instal... Read More

What is NPM in Node JS?

If you have ever worked with Node or any JavaScript framework, then you have already worked with NPM directly or indirectly. Let’s get into the details to understand more about NPM, and learn how to install the latest versions and manage different versions using NVM. In later articles we can discuss mastering basic tools like adding, updating or removing a package. We can also touch base on some advanced features like cache, audits, scripting and more. What is NPM ? To build an application with JavaScript or any other frameworks like Angular, React, Express or Node.js, we rely on a Package Manager to install its dependencies. This package manager is called as NPM. Note: Dependencies are the packages that are used in our projects and part of the package.json. NPM comes with Node.js and is pre-installed with Node. Package.json is the file containing the details of your project such as who created it, and what is the version of node and packages that your project is dependent on. A package is basically a set of files combined together to serve a specific interest of function. If we visit then we can search for different packages based on the functionality we need. For example, if you search for ‘date format’ to support multiple locales, we get 1171 packages (as on the date this article was written) with the topmost package being ‘moment’.  In short, if you are thinking of a functionality to build, then there is a high chance that there is a package already available in NPM for the same. As of January 2021, the current count is 1,493,231 packages.  NPM is used for building lightweight projects that can be easily shared across multiple development teams without dependencies being shared. It allows free use of resources and installs the dependencies only when needed. Install npm Node/npm can be installed on Mac, Windows or Linux as well. Let’s go through the steps involved in installing it on Mac. The approach should be similar for the other Operating systems. For Linux, refer to this. Navigate to and you will see the download section. Under the download, there is the other downloads link which will display different operating systems. Download the one specific to your Operating System. Double click on the node-v**.**.*.pkg to install the node. It is a simple wizard with straightforward steps. npm is installed with Node.js If you are wondering why we are installing node instead of NPM, this is because Node.js installs NPM along with it. This is evident from the below snapshot. How to check that you have node and npm installed The most common way to check if node or npm is installed is by looking at the terminal. Open terminal and Type in `node -v` and you should see the same version display in the installation wizard. The same applies to npm; i.e. You can type in ‘npm -v’ in terminal. On Versions - A note on versions, npm versions, Node versions and Long-Term Support When we are downloading the node.js from, we have two options; i.e. LTS and Current, both pointing to different versions, and currently on the higher version. LTS stands for ‘long time support’ and Current is the version that has the latest features, and offers support for 6 months. After 6 months, odd-numbered releases will become unsupported and even numbered ones will be given LTS status with support for 30 months. So, for all production applications, one should rely on Active LTS or Maintenance LTS releases. Current can be used for any trainings or by source contributors i.e. library authors.  Use a Node.js version manager Imagine you are working on an Enterprise application for an organization which uses a specific version of Node LTS. Also imagine that there is another app (it could be your pet project) that you are working on, for which you prefer to work on the latest version. But how can we have two different versions of Node in the same machine?  To achieve the same, we have NVM (Node.js version manager). Here is the official site for Mac and Linux users. Windows users can visit this link. Follow the installation steps to install the NVM on your machine.  To verify if NVM is installed correctly, open the terminal and type in ‘nvm --version.’ Type in ‘nvm list’ to display all the node.js versions that are installed on your machine. For now, you should be seeing only one version. Say you want to install an outdated version of Node.js, say 12. Type in ‘nvm install 12’ in terminal and it should install the 12 version of Node.js for you.  Now, type in ‘nvm list’ to see both the versions of node that are available for use. To switch to a specific version of node, type in ‘nvm use 12’. To check if it is the active one, type in ‘node -v’. Now you are good to go ahead with your project for that specific version of node.js. ConclusionNPM is one of the world's largest software registries. The Source contributors or developers are from across the world, and use npm to share or use packages. Many organizations/firms use npm for private development as well. NPM has 3 components i.e. Website, Command Line Interface and Registry.  We used the website to identify the package for ‘date format’ above. We learnt to set up private packages as well alongside public. The Command Line Interface is run from the terminal and is used by most of the developers, and the Registry is the public database of the JavaScript software.  
5635
What is NPM in Node JS?

If you have ever worked with Node or any JavaSc... Read More

Node.Js - Net Module

Node.js has a ‘net’ module which provides an asynchronous network API for creating stream-based TCP/IPC servers and clients. It can be accessed using: const net = require('net');  To create a TCP/IPC based server, we use the createServer method. var server = net.createServer(); The ‘server' object is of type net.Server. Let’s explore a few properties, events and methods on this class. First and foremost, the method needed is ‘listen’ which starts the server for listening to connections in async, firing the ‘listening’ event. server.listen(9000, () => {    console.log('opened server on port: ', 9000);  }); To find out on which address a server is running, we can use the address() method on the net.Server instance. If we need to log the port on which the server is running, then we can get this info as well without hardcoding. server.listen(9000, () => {    console.log('opened server on %j', server.address().port);  }); The first parameter of listen is the port in which the server starts listening, and a callback which gets called once it has started listening. A few of the common errors raised are:  ERR_SERVER_ALREADY_LISTEN – server is already listening and hasn’t been closed. EADDRINUSE – another server is already listening on the given port/handle/path. Whenever an error happens, an ‘error’ event is raised. We can hook to it and capture the errors accordingly. server.on('error', (e) => {    if (e.code === 'EADDRINUSE') {      console.log('Address in use, retrying...');      setTimeout(() => {        server.close();        server.listen(PORT, HOST);      }, 1000);    }  }); Whenever a client connects to this server then a 'connection' event is raised and in the callback we can get hold of the client object for communicating data. server.on("connection", (socket) => {    console.log("new client connection is made");  }); The second parameter is actually a callback which has the reference to the connection object, and the client object is of type ‘net.Socket’. To get the details like address and port, we can rely on remoteAddress, and remotePort properties respectively.   server.on("connection", (socket) => {    console.log("Client connection details - ", socket.remoteAddress + ":" + socket.remotePort);  }); Let’s assume that we are developing an application server like bot which needs to take inputs from clients and respond to the client. We can get hold of the client object and send messages to it from the server. As soon as the client is connected, we can send a sample return message on successful connection. server.on("connection", (socket) => {    console.log("Client connection details - ", socket.remoteAddress + ":" + socket.remotePort);    socket.write('SERVER: Hello! Connection successfully made.');  }); Now if there is any data being sent by client, we can capture that data on the server by subscribing to ‘data’ event on the client socket object.  socket.on('data', (data) => {    console.log(data.toString());// since data is streamed in bytes, toString is used.  }); Some of the most commonly used events on ‘net.Socket’ are data, error and close. As the names suggest, data is for listening to any data sent, error when there is an error happens and close event is raised when a connection is closed which happens once. Here is an example in server.js file: const net = require('net');  var server = net.createServer();  server.on("connection", (socket) => {    console.log("new client connection is made", socket.remoteAddress + ":" + socket.remotePort);    socket.on("data", (data) => {      console.log(data.toString());    });    socket.once("close", () => {      console.log("client connection closed.");    });    socket.on("error", (err) => {      console.log("client connection got errored out.")    });    socket.write('SERVER: Hello! Connection successfully made.');  });  server.on('error', (e) => {    if (e.code === 'EADDRINUSE') {      console.log('Address in use, retrying...');      setTimeout(() => {        server.close();        server.listen(PORT, HOST);      }, 1000);    }    else {      console.log("Server failed.")    }  });  server.listen(9000, () => {    console.log('opened server on %j', server.address().port);  }); ‘net’ module also has another class type net.BlockList. This helps in controlling or disabling the inbound or outbound traffic based on rules from any specific IP addresses, IP ranges, or IP subnets. Here is an example snippet from the documentation: const blockList = new net.BlockList();  blockList.addAddress('123.123.123.123');  blockList.addRange('10.0.0.1', '10.0.0.10');  blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');  console.log(blockList.check('123.123.123.123')); // Prints: true  console.log(blockList.check('10.0.0.3')); // Prints: true  console.log(blockList.check('222.111.111.222')); // Prints: false  // IPv6 notation for IPv4 addresses works:  console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true  console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true Now that we have the server up and running, we can build a client to connect to the server and start sending bi-directional data. This client could be another node.js application, java/c# application working with TCP sockets, asp.net MVC application talking to node.js TCP server or any other client application. But that client application should have TCP based communication mechanism support. Since we are talking about ‘net’ module, let’s build the client application as well using net module. Moreover, it supports TCP based communication as well. 'net’ module has a factory function called ‘createConnection’ which immediately creates a socket and establishes a connection with the server running on the specified port.  Let's create another client.js file and create a connection. const net = require('net');  const client = net.createConnection({ port: 9000 }, () => {    console.log('CLIENT: I connected to the server.');  }); The first parameter contains the details of the server. Since we are running the server locally, providing the port number would suffice for us as the host default address is localhost for TCP connections. The second parameter is the callback called once the connection is made successfully with the server. The returned value is of type net.Socket which we have learnt about earlier. Let’s hook to ‘data’ event and console log the information sent by the server. client.on('data', (data) => {    console.log(data.toString());    client.end();  }); Here we are not persisting the TCP connection and ending it once we receive a message from the server. We can subscribe to close event and handle any clean up needed. client.on('end', () => {    console.log('CLIENT: I disconnected from the server.');  }) The output on the client terminal has to be:  CLIENT: I connected to the server.  SERVER: Hello! This is server speaking.  CLIENT: I disconnected from the server. Output on server terminal will be: new client connection is made ::ffff:127.0.0.1:51680  CLIENT: Hello this is client!  client connection closed. In case we want to continue the client instance till the server is alive, we can comment out the ‘client.end()’ call. Any message in the terminal can be processed and sent to the server. For reading the text from terminal we use the readline module. Here is a complete example: const net = require('net');  const readline = require('readline');  const rl = readline.createInterface({    input: process.stdin,    output: process.stdout  });  const client = net.createConnection({ port: 9000 }, () => {  console.log('CLIENT: I connected to the server.');    client.write('CLIENT: Hello this is client!');  });  client.on('data', (data) => {    console.log(data.toString());    //client.end();  });  client.on('end', () => {    console.log('CLIENT: I disconnected from the server.');  })  rl.on('line', (input) => {    client.write(`CLIENT: ${input}`);  }); Both client and server now can communicate. When we type any text in client terminal, that is communicated to the server, and the server can respond back to the client via terminal.  ConclusionWebsockets help in creating a full-duplex connection for sending messages from client to server and vice-versa. Some of the real-time use cases that you may be familiar with are chat apps, IoT devices and so on. The Node.js net module helps you to create a server application easily, which can communicate to any type of client application like a web browser, mobile app, IoT device, Node.js client, or anything that knows TCP where the messaging need is bi-directional with streams. ‘net’ module can be used to communicate among child processes within a node.js server as well. 
5630
Node.Js - Net Module

Node.js has a ‘net’ module which provide... Read More