Angular Cheat Sheet
Monday, March 28, 2022Angular uses the latest technology known as Ivy. It is based on an incremental DOM. It is the code name for Angular’s next-generation rendering pipeline and compilation. From the very beginning of the release of Angular, the new compiler and runtime instructions are utilized instead of the older compiler and runtime which was known as View Engine. With the use of Angular Ivy including angular best practices, the developer can see that the compiler can easily generate a set of template instructions that are responsible for creating DOM elements, instantiating components, and running change detection. In this blog, our team has brought to you the angular cheat sheet for helping the developers.
1. Angular Cheat Sheet
Now, after understanding what Angular is and how it works, let us have a look at the Angular Cheat Sheet.
1.1 Angular CLI
The Angular CLI (command line interface) is one of the most straightforward, and fast ways of creating Angular applications. It is highly recommended by the Google community to create every Angular material. The Angular CLI enables creating several tasks trouble-free. Some of the major examples of these tasks are –
- ng build :- This compiles the app created in Angular into an output directory.
- ng serve :- This creates and serves the app for rebuilding on file changes.
- ng generate :- It enables generation or modification of files that are based on schematics.
- ng test :- It runs unit tests on your app development project.
- ng e2e :- Enables creating and serving an Angular app and later runs end-to-end tests on it.
You can see that Angular CLI is a very valuable tool for developers as it makes their development tasks easy. And this is why it is a part of the Angular cheat sheet.
1.2 Modules
As you all know, the apps created using Angular are modular. The modularity is known as NgModules. NgModules are nothing but containers for a cohesive block of the app code dedicated to the domain of the app, a workflow, or a set of capabilities that are very closely related to the application.
1.3 Built-in Directives
For creating an Angular application, the developer can import the built-in directives from the angular/common module. The command line for importing it is as follows –
import { CommonModule } from '@angular/common';
There are four major types of built-in directives and we will go through all four of them.
The above command enables the developers to create and hide or we can say completely remove the element of the code as per the show expression value in the component.
This enables theli element as a template. After that, it uses the contents of the user’s array to immediately create a view for each item that is included in the list. It is just like using for Each function in JavaScript to develop a view for each element that is included in an array. Besides, the ngFor directive in this command line can only be used on strings or arrays.
...
...
It is a command line that swaps the content of the div according to the value of the condition present in the expression. Then the content shifts into the case as per the specified value. This is just like the Switch attribute in JavaScript.
The above-specified command line binds the CSS class active to the element according to the isActiveexpression, which can be either true or false.
1.4 Directives
Directives are known as markers in the DOM (Document Object Model) at a high level. The developers use directives with any HTML tag or controller which tells the compiler what behavior or operation is expected. Some of these directives are predefined but developers can create a new directive if they want. These directives are known as custom-directives.
Let us have look at the top directives with their description in Angular –
ng-app :- Enables the developers to start AngularJS application.
ng-init :- Developers use it to initialize a variable.
ng-model :- It is used in property binding of the HTML controls.
ng-controller :- It attaches a controller to the view.
ng-bind :- Enables binding of the value with HTML element
ng-repeat :- It enables the developers to repeat the HTML template once for each item in the collection that is specified.
ng-show :- It shows or hides(removes) the associated element of HTML.
ng-readonly :- This directive makes HTML elements in the form of read-only.
ng-disabled :- It is a directive used by developers to enable or disable a button dynamically.
ng-if :- It helps in removing or recreating HTML elements.ng-click :- It enables a custom step on click.
1.5 Structural Directives
When it comes to structural directives in Angular, there are two main directives – NgFor and NgIf.
The ngIf directive is a popular directive used to add or remove an element of HTML from the DOM according to a certain condition. The value that the developer passes to ngIf should either be an expression that appraises a boolean value or it should be a boolean value itself. For instance –
Another structural directive – NgFor is used by the Angular developers to render HTML elements on the page that are based on an array. For instance –
users: any[] = [{
"name": "Victor"
}, {
"name": "Bruce"
}, {
"name": "Thor"
}, {
"name": "Pitter"
}];
1.6 Forms
Forms are nothing but a great collection of controls that is a button, input field, or checkbox. These controls can be validated in real-time. This means that onces the user of the form enters data into a field and moves to the next one, the system validates and suggests to the user if he has entered any wrong value. Forms in Angular consists of many different controls, some of them are –
- Input field
- Radiobox
- Checkbox
- Button
- SelectBox
First we need to import FormModule in the app module
@NgModule({
imports: [
BrowserModule,
CommonModule,
FormsModule
],
declarations: [
AppComponent,
FormComponent
],
providers: [],
bootstrap: [ AppComponent ]
})
Template Driven Form can be used to post the data from html to ts file using below code.
Here onSubmit() is an event which calls a function in .ts file where the updated model data from the FORM can be retrieved.
1.7 Reactive Forms
Reactive forms in Angular offer a model-driven approach that enables developers to handle the inputs of the forms whose values might change over time. This type of form uses an explicit approach to manage the form at any given point of time. Each change made to the form state returns a new state and this helps in maintaining the integrity of the model in the middle of the changes. Besides this, reactive forms are created around observable streams. This is done when the form inputs and values are offered as streams of input values and these values can be easily accessed synchronously.
First we need to import ReactiveFormsModule in the AppModule
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
Reactive forms are defined at .ts level and then each form control can be mapped to different inputs of the form in Html side.
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
name = new FormControl('');
}
We can bind above Form Control in html as below
1.8 Form Groups
Form groups is the most used approach in angular. Here we group together different form controls in a FormGroup and can apply validations for required controls and we can also set max and min length from the ts side only.
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-person-editor',
templateUrl: './person-editor.component.html',
styleUrls: ['./person-editor.component.css']
})
export class PersonEditorComponent {
personForm = new FormGroup({
fName: new FormControl(''),
lName: new FormControl(''),
});
}
We have to define a <form> tag in html which has the attribute [formGroup] as below.
1.9 Data From Parent to Child
It is very important to have a technique to pass data from parent component to child so that we do not need to initiate that data again in the child component. We use property binding on the HTML DOM to implement it.
Let’s say we have a component <app-child> and we need to pass userData from parent component to child component then we need to use Input property at child level and using the same property we can bind the userData to the child from the child selector html as below.
parent.component.html
child.component.ts
@Input() user: any;
In the above example we have some data about the user in the parent component stored in a variable userData which we are passing to the child component’s variable user. We can use the user variable in the child component to bind the user’s properties like first name, last name, age to the child’s Html.
1.10 Data From Child to Parent
It is very important to have a technique to pass data from the child component to the parent component once we change it on the child level.
Let’s say we have a component <app-child> and we need to pass responseData from child component to parent component then we need to use the Output property at child level and define a variable of type EventEmitter();
At the parent component we need to listen to this event from the child’s html selector and pass the event data to any method to handle it at the parent level.
child.component.ts
@Input() responseEvent = new EventEmitter();
…
getResponse(value){
this.responseEvent.emit(value);
}
parent.component.html
parent.component.ts
handleResponse(value){
console.log(‘Response from child’, value);
}
In the above example, the child is emitting a response to the parent component using responseEvent as an event emitter which emits the event data to the parent.
On the parent component, we are receiving the event data through (responseEvent) and passing it the function handleResponse().
1.11 Class Decorators
Angular provides four main decorators named class decorator, property decorator, method decorator, and parameter decorator. But the most used one is the class decorator. This type of decorator enables the developers to tell Angular a particular class is a module or a component.
Here’s how a class decorator is imported from the core module of Angular.
import { Directive, ...} from '@angular/core';
You can replace the Directive with the decorator that you wish to use.
@Component({...})
class AppComponent() { }
This enables you to declare that the class is a component and also offers the component’s metadata.
@Directive({...})
class CustomDirective() { }
This command line declares that the class is a directive and offers its metadata.
@Pipe({...})
class CustomPipe() { }
This helps the developers to declare that the class is a pipe and offers its metadata.
@Injectable()
class CustomService() { }
This command-line specifies that the class contains dependency injectors.
1.12 Template Syntax
When it comes to managing an Angular application, what the user sees and does is achieved through the interaction of the user-facing template and component class instance. Angular components plays a very big part of the view models or controllers while the template represents the view in the template-driven forms. To understand more, let us go through some of the template syntax for the HTML.
This code line helps in binding the value of the expression firstName from the component.
This is the command line that enables the developers to bind the attribute role of the expression myRole to the result from the component.
This line will help you bind the CSS class to the div element. And this depends on if the expression, isActive in the component is false or true.
1.13 Routing
Routing is one of the most important features in the list of Angular cheat sheets. Angular offers route instruction consisting of adding route guards and navigating through pages.
When it comes to component routing, the developer needs to define routes in the app by defining the component and the path to be rendered:
const routes: Routes = [
{ path: 'home', component:HomeComponent },
{ path: 'blog/:id', component: BlogPostCompoent },
{ path: '**', component: PageNotFoundComponent }
];
To make the routing work in the Angular project, the developer needs to add this to the app.module.ts file:
RouterModule.forRoot(routes)
There are various situations where the developer needs to keep track of what is actually happening on the root route: the developer can add this to enable tracing in the project.
RouterModule.forRoot(routes,{enableTracing:true})
And to navigate through the pages of the project in Angular, one can use the routerLink, the attribute that takes the component’s name that you are routing.
Crisis Center
In Angular routing, routerLinkActive=”active” is a code line that will help in adding an active class to the link when it is in an active state.
1.14 Lazy Loading
An Angular application is a single page application that loads everything at once and It renders the component in <router-outlet> when the route gets changed. Let’s talk about a bigger application where we have multiple modules and each module contains a number of components and routes. Angular application initial loading time increases as the application is trying to load all the modules and components and to avoid this situation, we use lazy Loading.
Lazy loading is basically on-demand loading, which means it loads a particular module and its components only when it’s needed. It does not load all the modules together.
To implement Lazy-Loading the application must be divided into separate modules based on different functionalities. Now each module must have its own routing module which regulates the routing of components inside that particular module. Here the AppRoutingModule contains routing to each module within the application and would look like below.
const routes: Routes = [
{
path: 'items',
loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
}
];
Here the application redirects to the component which is defined in the items routing module, let’s say ItemsComponent in the below case and it does not load any other module. Items routing module would look like below
const routes: Routes = [
{
path: '',
component: ItemsComponent
}
];
1.15 Routing and Navigation
In a single-page application, app development experts can change what the user can see by hiding or showing portions of the display that correspond to specific components rather than going out to the server in order to get a new page.
Besides, to handle the navigation from one view of the form control to another in the Angular application, one can use the Angular Router. It enables navigating by simply interpreting a browser URL.
1.16 Bootstrapping
Developers bootstrap the Angular app with the use of the root component from the particular NgModule.
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));
1.17 Angular Components and Directives Change Detection and Lifecycle Hooks
Be it a parent component or a child component in Angular, there are many different phases for components. We can hook into some of those phases to get control of the Angular application. Here are some of the Angular Lifecycle Hooks –
- ngOnChanges:- This directive is called when any one input properties changes.
- ngOnInit:- It is called as soon as ngOnChanges is completed.
- ngOnDestroy:- It is called before the Angular system destroys a component or a component.
- ngDoCheck:- This directive is called when a change detection is running.
- ngAfterViewInit:- This directive is called when the component’s view is completely initialized.
- ngAfterViewChecked: It is invoked every time the view is given a component that has been checked by the change detection system.
2. Conclusion
As seen in this blog, there are various factors included in the Angular cheat sheet which can be very helpful to the Angular development team if they follow it properly. These factors are the most essential part of the Angular life cycle and enable the application to run perfectly.
More Resources on Cheat Sheet:
React Cheat Sheet
Node Cheat Sheet
Comments