Angular Cheat Sheet
Contents
What is Angular?
Angular (commonly referred to as “Angular 2+” or “Angular v2 and above”) is a TypeScript-based open-source web application framework, developed and maintained by Google.
Traditionally, VanillaJS and jQuery were used by developers to develop dynamic websites. As the websites became more complex with added features and functionality, it was hard for the developers to maintain the code.
Angular is designed to enable you to build and manage shared code, and to divide work among appropriate roles.
Angular is a complete rewrite from the same team that built AngularJS.
AngularJS | Angular |
---|---|
Doesn’t Support DI | Supports DI |
Doesn’t Support Rest | Supports REST |
Doesn’t provide mobile support | Provides mobile support |
Uses JavaScript | Uses TypeScript |
Architecture
Angular file system has a file called angular.json, which defines main.ts as the entry point of the application, which in turn defines AppModule as the bootstrap module.
Modules
In Angular, a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application.
Modules are of two types:
- Root Module
- Feature Module
Every application can have only one root module whereas, it can have one or more feature modules. A root module imports BrowserModule, whereas a feature module imports CommonModule.
Modules in Angular are decorated with @NgModule decorator.
Components, Directives & Pipes
Components
Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template.
Components in Angular are decorated with @Component decorator.
@Component({
selector: 'app-bank-account',
inputs: ['bankName', 'id: account-id'],
template: `
Bank Name:
Account Id:
`
})
export class BankAccountComponent {
//default method of the class
constructor(){
}
//life cycle hooks
ngOnChanges(){}
ngOnInit(){}
ngDoCheck(){}
ngAfterContentInit(){} //hook for children
ngAfterContentChecked(){} //hook for children
ngAfterViewInit(){} //hook for children
ngAfterViewChecked(){} //hook for children
ngOnDestroy(){}
/*
ngDoCheck and ngOnChanges should not be implemented
together on the same component.
*/
}
Directives
There are three kinds of directives in Angular:
- Components — directives with a template.
- Structural directives — change the DOM layout by adding and removing DOM elements. These directives have a * sign before the directive. For example, *ngIf and *ngFor.
- Attribute directives — change the appearance or behavior of an element, component, or another directive. Attribute directives are used to change the look and behavior of the DOM element. It provides the facility to create our own directive.
Directives in Angular are decorated with @Directive decorator.
Pipes
A pipe gets data as an input, transforms it and outputs this data in another way. Pipes in Angular are decorated with @Pipe decorator.
Services & Dependency Injection:
Dependencies in Angular are services which have a functionality. Various components and directives in an application can need these functionalities of the service. Angular provides a smooth mechanism by which these dependencies are injected into components and directives.
There is a risk that a lazy loaded module will try to create a 2nd instance of a service what should be a singleton, and the forRoot() method is a way to ensure that the app module, shared module and any lazy loaded module all use the same 1 instance (the root instance).
//old way
@NgModule({
imports: [
SharedModule.forRoot()
]
})
export class AppModule { }
//or the preferred way beginning with Angular 6.0
@Injectable({providedIn: 'root'})
export class SharedService {}
Providers are classes that create and manage service objects the first time that Angular needs to resolve a dependency. Providers describe how the Injector should be configured.
Services in Angular are decorated with @Injectable decorator.
Routing
In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. As users perform application tasks, they need to move between the different views that you have defined.
To handle the navigation from one view to the next, you use the Angular Router. The Router enables navigation by interpreting a browser URL as an instruction to change the view.
It is modeled on the familiar browser navigation conventions:
- Enter a URL in the address bar and the browser navigates to a corresponding page.
- Click links on the page and the browser navigates to a new page.
- Click the browser’s back and forward buttons and the browser navigates backward and forward through the history of pages you’ve seen.
//app-routing.module.ts
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
export const routes: Routes = [
//loading a normal component
{
path: 'home',
component: HomeComponent,
},
//loading a lazy loaded module
{
path: 'auth',
loadChildren: () => import('./auth/auth.module')
.then(m => m.NgxAuthModule),
},
//default component if url doesn't match any path.
{ path: '**', redirectTo: '404' },
{ path: '404', component: NotFoundComponent }
];
const config: ExtraOptions = {
useHash: false,
};
@NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule],
})
export class AppRoutingModule {
}