Search

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

Essential Angular 9 Development Cheat Sheet

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

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

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

Everything You Need To Know About Angular 12.0.0 Release

Angular is a product of the most renowned Google TypeScript based framework, dedicated to developers for building web applications for smartphones and desktops. Over the years, the Angular framework has shown significant growth and is now a favourite tool among developers. The popularity of Angular can be attributed to the fact that it has been reliable and offers unmatchable features which are easy to use, when compared to its competitors, since its official launch.The popularity and increasing demand for the Angular framework are scaling new heights. From its first release to date, the Angular framework has attracted developers and has been marked as the favourite of over twenty-six percent (26%) of web developers worldwide. Angular provides unmatchable features that make it the most preferred framework in the Web Development industry today.   The frequent updates by the Angular team are just another reason to fall in love with this most versatile and robust framework. With every subsequent update, the Angular team brings in new features, extended capabilities, and functionalities that make the user experience effortless and web development enjoyable.   Glad tidings for Angular developers! Angular 12 tries to improve on fixing bug issues in the previous versions that were raised by the Angular community. Finally, the wait is over! The Angular version 12.0.0 release has come up again with the most compelling features and customization options to take your development journey to a new horizon. The new release of the Angular 12.0.0 version brings updates on the framework, the CLI, and components. What’s new in this update? The Angular team has been releasing major features in their upgrades, while ensuring that the number of backward compatibility issues is kept at a minimum and making sure that updating to the new version is easy. We have seen significant improvements in these areas of built times, testing, built-size, and development tooling. Before the release of Angular on the 21st of April, 2021 there were 10 beta versions of the same.  Updates in Angular 12 include the following: For the language service, they have added a command to add a template file. Making minified UMDs essential. Redirected Source files. Component style resources. Introduction of a context option.  New migration that casts the value of fragment nullable. DOM elements are correctly removed when the root vies have been removed. Improved performance since unused methods have been removed from DomAdapter. Legacy-Migrate. Strict Null checks. App-initializer has been changed. Support has been added for disabling animations.  Angular 12 can disable animations through BrowserAnimationsModulewithconfig. Addition of the emit event option. More fine-tuned controls in routerLinkActiveOptions. Custom router outlet implementations are permitted. Support for type screen updated. Implementing the append all() method on Httpsparams. Minimum and maximum validators are introduced. Exporting a list of HTTP status codes. New Feature in Angular Service. Patch adding the API to retrieve the template type check block. NOTE: Several bug fixes have also been highlighted, affecting the compiler, compiler-CLI, Bazel-built tool, and the router. Let’s have a look at the unique and unparalleled features in Angular 12.0.0:  1. Better developer ergonomics with strict typing for @Angular/forms. The Angular team has focused on enforcing secure and strict methods of checking for reactive forms. The new update will help developers to look out for issues in the development stage. This upgrade will also enable better text editor and ide support allowing the developer better developer ergonomics with strict typing for Angular/forms. The previous versions were not as aggressive in addressing this issue, but Angular 12 does it perfectly. 2. Removing legacy View Engine. When the transition to Ivy of all internal tooling gets done, removing the legacy View engine becomes the next challenge. No worries! The newly added removing legacy View Engine aims to reduce framework overheads. This is because of smaller Angular conceptual overhead, smaller package size, saving on maintenance cost, and decrease in the complexity of the codebase. With the knowledge of Ivy, it's the best path to take while using the latest version of Angular. An application that has upgraded to the latest version of Angular (Angular 12.0) and is keeping enable Ivy as false, should consider this since in the future they cannot upgrade to the latest version if they don't start using Ivy. 3. Leverage full framework capabilities.  Design and implement a plan to make Zone.js optional. This will, in turn, simplify the framework, improve debugging, and minimize application bundle size.Zone.js does not support native async/await syntax and when Zone.js is optional and a developer can choose not to use it then Angular will be able to support native async/ await syntax. 4. Improving test time, debugging, and test time environment. Testbed automatic clean-up and tear down of the test environment after each test run, will improve test time and create better isolation across tests. 5. Easier Angular mental model with optional modules. This will simplify the Angular mental model and learning. This will allow the developers to develop standalone components and implement other types of APIs for the declaration of the component compilation scope. On the other hand, we have to note that this change might make it hard for existing applications to migrate to this. This feature will allow developers to have more control over the compilation scope for a particular component without giving much thought to the NgModule they belong to. 6. Adding Directives to Host Elements. Adding directives to host elements has been on high request by Angular developers for a long time. The new release allows developers to architecture their components with additional characteristics without using inheritance. At the moment you cannot add directives to host elements, but you can improvise using: host CSS selector. As the selector of these components also becomes a DOM element, we could have more possibilities if we could add more directives to this element too.7. Better Build performance with NGC as TypeScript plugin distribution.The Angular compiler being distributed as a TypeScript plugin will significantly improve the developer's build performance and reduce the cost. 8. Ergonomic Component level code-splitting APIs. The slow initial load time is the major problem with web applications. Applying more granular code-splitting on a component level can solve this problem. This will mean smaller builds and faster launch time and in return result in improved FCP.  That's all for the new release. Now, let us take a look at the possibilities that are in progress and will be available shortly. Inlining critical styles in universal applications. Firstly, this will result in faster applications. Loading external stylesheets is a blocking operation. This means that the browser cannot initiate rendering an application without first loading all the referenced CSS. Its FCP (First Contentful Paint) can be improved by having a render-blocking in the header of a page that can visibly improve the load performance. Angular language service to Ivy. To date, the Angular language service still uses the View Engine compiler and type checking even for Ivy applications. The goal is to improve the experience and to remove the legacy dependency. This will be achieved by transitioning from View Engine to Ivy. The team at Angular wants to start using the Ivy template parser and improved type checking for the Angular language service to match Angular application behaviour. This will simplify Angular, npm size reduction, and improve the framework’s maintainability. Debugging with better angular error messages. The error messages bring limited information on how a developer can take actions to resolve them. The Angular team is working on codes, developing guides, and other measures to ensure an easy debugging experience and make error messages more discoverable. Better security with native Trusted Types in Angular. In conjunction with the Google security team, the Angular team is working on adding support for the new Trusted Type API. This API will aid developers to make more secure web applications. Optimized build speed and bundle size.With Angular, the CLI Webpack 5 stability will continue urging for the implementation to enable build speed and bundle size improvements. Advanced Angular Material Components. Integrating MDC weblink will align Angular Material closely with the material design specification, expand the accessibility reach, improve component quality and improve the overall team velocity. Faster debugging and performance profiling. The team at Angular could focus its attention on working on tooling that will help in the provision of utilities for debugging and performance profiling. The primary aim is to help the developers understand the component structure and the means to note changes in the angular application. NOTE: MDC web is a library created by the Google Material Design team that provides reusable primitives for building material design components. Conclusion.   In this article, we have looked at the Angular 12.0.0 version that released on 21 April 2021, the predecessor of which was Angular 11. We have tackled all the new features and provided an in-depth explanation of the same. We have taken a look at the trajectory of the Agular team whilst discussing the possibilities of new features to come in future versions of this product.  Angular is becoming more robust, and the applications created on this platform are getting more performant with every new update of the product. The framework is the future of this product, and this does not mean they are all necessarily in version 12.0.0. There are more points to be added to this list for internal improvements, such as work on the Angular team performance, dashboard, and so forth. Angular developers may be looking out for more advanced features like those present in Ivy-based language service. Perhaps those are slated for the next release! Attention Coders: If you want to know more about Angular version 12 and plans for the framework, you can visit their website
7313
Everything You Need To Know About Angular 12.0.0 R...

Angular is a product of the most renowned Google T... Read More

What Is Replication in MongoDB

What is Replication? Replication is the process of storing the data in multiple places instead of just one. Data is stored on multiple servers across different physical sites, in order to improve data availability and also ensure uninterrupted access to data even if one of the sites goes down due to some failure. Simply put, replication involves copying of the data from one server to another. As the changes occur on the primary server, they are simultaneously propagated to the other servers as well. This keeps all of the servers in sync and the read operations can be performed on any of the available sites. The result is a distributed database in which users can access data relevant to their tasks without interfering with the work of others. Replication in MongoDB In MongoDB, mongod is the primary process in the system that handles data requests, manages data access, and also performs various background management operations. For Replication to work, it is important to have multiple mongod instances running that maintain the same dataset.  A replica set is the foundation of replication. The server instances that maintain the same dataset form a replica set in MongoDB. A replica sets ensures redundancy and high availability, and is the basis for all production deployments. Each replica set contains multiple data bearing nodes and optionally an arbiter node. Of all the data bearing nodes, one and only one member is designated as the primary node, while the other nodes are designated as the secondary nodes. The primary node receives the requests for all the write operations from the clients. The write operations are then synced to the secondary nodes using various algorithms. The primary records all writes and other changes to its datasets in its operation log, i.e. oplog.To enable replication in MongoDB, a minimum of three nodes are required. In this operation of replication, MongoDB assumes one node of replica set as the primary node and the remaining are secondary nodes. From within the primary node, data gets replicated to secondary nodes. New primary nodes get elected in case there is automatic maintenance or failover. Redundancy and Data Availability If replication is in place, it simply means that there will be multiple copies of the same data in different database servers. This ensures high data availability and data redundancy. High availability indicates a system designed for durability, redundancy, and automatic failover such that the applications supported by the system can operate continuously and without downtime for a long period of time. Due to redundancy, replication provides fault tolerance against the loss of one or more (not a lot) database servers. In certain cases of data replication, clients can send read operations not just to one server, but to different servers. This results in increased read capacity and faster responses to requests from clients. Maintaining copies of data in different servers increases data locality and availability for distributed applications. These duplicate copies of data can be used for various recoveries, reporting or backup purposes as well. Enabling Replication in MongoDB As we already know, a replica set is a group of mongod instances that maintain the same data set. A replica set contains several data bearing nodes and, in some cases, one arbiter node which is optional. Of all the data bearing nodes, one and only one member is designated to be the primary node, while all the other nodes are assigned to be secondary nodes. The point of an Arbiter is to break the deadlock when an election needs to be held for a Primary.  If you have an odd number of nodes, the election process is simple when all nodes are up, and in a failover, one of the other nodes will simply be elected. If you have an even number of nodes in a replica set, an Arbiter may be required. An example is a case where you do not want to commit the same level of hardware to have, say, a five-node replica set. Here you could use an arbiter on a lower specification machine in order to avoid a deadlock in elections. An arbiter is also useful if you want to give preference to certain nodes to be elected as the Primary.The primary node receives all write operations. A replica set can have only one primary capable of confirming writes with { w: "majority" } write concern. The primary records all changes to its data sets in its operation log, i.e. oplog. The secondaries replicate the primary’s oplog entries and apply the operations to their datasets such that the secondaries’ datasets completely reflect the primary’s dataset. If the primary is unavailable, an eligible secondary holds an election to elect itself as the new primary.  In some cases where, for example, cost constraints allow only one primary and secondary but do not allow addition of more than one secondary, an arbiter is used. An arbiter node does not hold any data at al. It only participates in elections. Hence, it does not provide any data redundancy.  An arbiter will always be an arbiter, whereas a primary may step down and become a secondary, and a secondary may become the primary during an election. Follow the following steps to enable replication and create a replica set.Ensure that all servers can access each other over the network. For now, consider that we have 3 servers, ServerA, ServerB and ServerC. Considering the ServerA is the primary and only server working as of now, issue the following commands on server A. mongo –host ServerB –port 27017 mongo –host ServerB –port 27017 Execute the same commands on the remaining servers as well. Start the first mongod.exe instance with the replSet option. This option provides a grouping for all servers which will be part of this replica set. mongo –replSet "Replica1"The first server is automatically added to the replica set. Next, let’s initiate the replica set. rs.initiate() To add more servers to the replica set, issue the following commands.rs.add("ServerB")rs.add("ServerC")You’re done! Run the rs.status() command. This command gives the status of the replica set. By default, each member will send messages to each other called "heartbeat" messages which just indicate that the server is alive and working. The "status" command gets the status of these messages and shows if there are any issues with any members in the replica set. Benefits of Replication We already know that Replication allows us to increase data availability by creating multiple copies of the data across servers. This is especially useful if a server crashes or if we experience service interruptions or hardware failure. Let’s have a look at some other advantages of Data Replication. Replication helps in disaster recovery and backup of data. In case of a disaster, secondary nodes ensure that the data is always available without service interruptions. Replication ensures that data is always available to every client. Replication keeps the data safe and protected through this redundant backup approach. Replication minimizes downtime for maintenance. Asynchronous Replication Asynchronous replication is a replication technique where data is backed up periodically or after a period of time. It is not immediately backed up during or immediately after the data is written to the primary storage. This kind of replication results in good performance and lesser bandwidth requirements, but the backups are not readily available if something happens to the primary storage.In an asynchronous replication system, the data is written to the primary storage first and then it is copied over to the secondary nodes. The copying or replication is done at predetermined intervals. How and when this is done, depends on the settings and the type of implementation of asynchronous replication.This method allows for good read/write performance without adversely affecting the bandwidth usage as data is not replicated to remote backups in real-time, as in a synchronous replication system. So the system in not under a lot of load at any given point of time. Data is only backed up after predetermined times or periodically. This does not guarantee 100% backup, so it should be used for less sensitive data or information that has tolerance for loss. In a situation where a disaster or failure occurs right after the data is written to the primary storage, the data will not be copied over to the secondary nodes and therefore will cause loss of data and affect availability. Replication vs Sharding Sharding is a process where the scaling is done horizontally by partitioning data across multiple servers using a special key called Shard Key. A sharded environment does add more complexity because MongoDB now has to manage distributing data and requests between shards -- additional configuration and routing processes are added to manage those aspects.Replication, on the other hand, creates additional copies of the data that allows for better availability and read performance. Typically, replication and sharding are used in combination. In these situations, each shard is supported by a replica set.Shards in MongoDB are just replica sets with a router in front of them. The client application connects to the router, issues queries, and the router decides which replica set (shard) to forward the request to. It is significantly more complex than a single replica set because we have the router and configuration servers to deal with.Sharding is done with the objective of scaling the database horizontally.Transactions Multi-document transactions are available for replica sets (starting from version 4.0). Multi-document transactions that contain read operations must use read preference primary. All operations in a given transaction must route to the same member.The data changes made in the transaction are not visible outside the transaction until a transaction commits. Once the transaction commits, changes are then available to be read by all secondaries and clients.However, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards.Change streams In replication, as we have read above, the secondary nodes replicate the primary node’s oplog entries and end up having exactly the same dataset as the primary. Another alternative to this approach is that whenever there is a write to the primary node’s data, it informs all the secondaries of this data change and the secondary nodes then update themselves accordingly. This is possible with the help of change streams.Change streams allow applications to subscribe to all data changes on a collection or a set of collections. This way all the apps are notified of the changes to the data.Replica sets provide a number of options to support various application needs including data backup, recovery and increasing availability. They increase performance and data availability. Replication also ensures that the downtime, if there is any, is brought down to lowest in case of disaster or any other event that causes interruptions in accessing data.
7349
What Is Replication in MongoDB

What is Replication? Replication is the process o... Read More

Difference between State and props in ReactJs

In this article, we will discuss the states and props in ReactJS. Props and state both provide the details about the item but have differences. Let’s take a look at how to pass props into the component and how to update a component’s state.What is State?The status of a react class component instance can be described as an object of a collection of observed features that control the component’s behavior. In other words, the component’s state is an entity with some details that can alter during the component’s lifetime.This data is kept inside a component. This particular aspect is local or owned. The component itself uses the setStatus function to update the state. The state is an updated structure that is used to contain and can modify data or information about the component over time. The state change may occur as a user activity or device event response. It decides the actions of the component and how it is to be done by the core of the React component. As easily as possible, a state should be held. It is the local state or details of the part. Only in the component or by the component directly can it be accessed or changed. Components of react have a built-in state object. The state object is where the property values belonging to the item are stored. The component is restored when the state object changes.What are Props?React is a library focused on components that separate the user interface into reusable little bits. These components have to transmit (send data to each other) in some cases, and the way to transmit data among components is through props. “Props” is a special React keyword for proprietary purposes, used for data transmission from component to component. But the key part of this is the transmission of data with props in a uniform flow. (parent-to-child route)In addition, props data are read-only, meaning that parent data cannot be modified by child elements.Difference between State and PropsReact is an opensource JavaScript library that offers a visual overview of the JavaScript architecture for conventional MVC. React promises programmers a model in which substrates cannot directly influence enclosing components—data are downstream, data changes in HTML are efficiently modified, and the DOM is abstracted to boost performance using Virtual DOM.How can we access data from the previous component if the data is just being flowed from components to components? The answer is props. React uses data transmission props that we need to transfer to various components. The difference comes in which component the data are owned. State is owned locally and the component itself updates it. Props are owned and read-only by a parent. Props can be changed only if an upstream shift is caused by a callback function passed on to the child.A prop can be passed on to the child in the state of a parent. They apply to the same value but can only be updated by the parent variable.How are props passed into the component?We can pass props to any component by declaring HTML tag attributes.We transfer a sampleProp in the above code snippet to the DemoComponent part. This prop has the ‘HelloProp’ value. See how we can access this advice now.In the class components to which the props are transferred, we can access any props.this.props.propName;We can use the above syntax to access any prop from within a component class. The “this.props” is a type of total object that stores all props from an item. The propname, which is the propName, is the key.Passing information from one component to other:This is one of React’s coolest characteristics. We should make it possible for components to communicate. To understand this, we will look at two components Parent and Child. We will pass information to the Child component as advice from our parent component. We can offer a part as much advice as we want. The content of a prop is not permitted to be changed. No matter what kind of component it is, nobody is allowed to change their advice, whether functional or class-based. The difference comes in which component the data are owned. State is owned locally and the component itself updates it. Props are owned and read-only by a parent. Props can be changed only if an upstream shift is caused by a callback function passed on to the child. A prop can be passed on to the child in the state of a parent. They apply to the same value but can only be updated by the parent variable.How do you update a component’s state?Although a react component can have an initial state, the actual power is in updating the state — the component should not be in either state if we don’t have to update the state. State is reserved only for data that changes our part and can be seen in the user interface.We use this.setState() instead of changing the state directly using this.state (). This is a feature for all components that use state, and allows us to inform React that the state of the component has changed. This way the component knows that it can return because its status has changed and the user interface will probably change as well. It is very efficient to use a setter function like that. React intentionally waits until all components in their event handlers call setState() before they start returning. This increases efficiency by preventing excessive re-renders. You may also ask why React does not update this, however. Two major reasons exist: The consistency of props and the state is broken, which causes problems that are very difficult to debug. This will make it difficult to introduce such new features. React will load several setState() calls for performance into a single update. Due to the asynchronous of this.props and this.state, you cannot depend on their values for the next state to be calculated. To fix it, use a second setState() form, which accepts a function instead of an object. This function is the first argument for the previous state, and the props are the second argument when the update is applied: this.setState(function(state, props) {   return {     counter: state.counter + props.increment   }; });Is state changeable?A state change takes place on the basis of the user input, which triggers an occurrence. React (with status) components are often made on the basis of state data. The initial knowledge is held by the State.Thus when the state changes, React will be notified and the DOM will be re-rendered immediately; not the whole DOM but only the modified portion. This is one of the reasons for the fast reaction.And how do you notify React? You thought: with setState ( ). The setState() method triggers the mechanism for rendering the modified components. React is notified, knows which part(s) to alter, and does so quickly without restoring the entire DOM.Is state created in the component?Let’s see the constructor method:constructor() {   super();   this.state = {     count: 0,   }; }This is where the state gets the initial data. The initial data (as above) can be hard-coded, but it can also come from props.However, it makes sense – you cannot adjust props but the data a component receives wants to do so. This is where the state enters.Component typesStateless component — Just props, no state.  Besides the render() function, there’s not much going on and all its logic is about the props that they get. This makes it easy to track them (and test for that matter).  The stately component — state as well as props. These are also called state managers. They are responsible for communication between clients and their servers (XHR, Web sockets, etc.), data processing, and user events.What happens when state changes?React Components allow you to break the UI into separate, reusable components so that you can look into every single item on an isolated basis.Components are conceptually like functions in JavaScript. They accept arbitrary inputs and return elements of react that describe what should be shown on the screen. If you have to allow the user to enter something or to alter the variables that the component is supported by, you would have to setState.State allows React components in response to user behavior, network responses, and everything else to adjust their performance over time, without violating this rule. Class-defined components provide additional functionality. Local status is the only class component function available.Can I use state in every component?In the early days, only class components, and not functional components, were included.That’s why stateless components are known for their functional components. However, state can now be used in both class and functional components following the implementation of React Hooks.You can only use status in class components if your project does not use React Hooks.The component State and Props share some common similaritiesProps and states both provide details about the item, but they are used differently and must be kept separate.ConclusionState refers to the component’s local status which cannot be used and changed outside the component and can only be used and modified within the component. On the other hand, it provides reusable components by enabling components to obtain data in the form of props from the parent component. We may change the state of a component with setState. These notifications are also triggered by events. setState is called asynchronous and merged with every entity in the current state. We may also transfer a setState function to allow us to write status changes based on the current status values. Most of your components can be stateless when you create an app. Props transfer parent-to-child data. They are unchangeable and are thus unchanged.
1680
Difference between State and props in ReactJs

In this article, we will discuss the states and pr... Read More