## Essential Angular 9 Development Cheat Sheet

### Reactive Forms in Angular

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

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

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

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

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

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

The Angular Router

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

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

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

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

<router-outlet></ router-outlet>

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

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

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

### Auth Guards

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

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

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

ng generate guard AuthGurard

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

Here is an example implementation of the function, canActivate

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

Build the App

The Angular CLI allows you to build the app.

ng build

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

ng build --prod --outputPath=myBuildFolder

There are a few more flags available.

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

Conclusion

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

Some of the most common external packages for Angular are -

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

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

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

## Everything You Need To Know About Angular 12.0.0 Release

7313
Everything You Need To Know About Angular 12.0.0 R...

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