Learn how to create a cheat sheet for Angular 2

0
5354
cheat-sheet

In this chapter, we are going to discuss the various Angular 2.0 syntaxes that could be used as cheat codes for Typescript to build Angular 2.0 application very swiftly.
Bootstrapping

S No.

Syntax

Import

Description

1.

platformBrowserDynamic ().bootstrapModule (AppModule);

import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;

This cheat code is used to Bootstrap the angular 2.0 app that uses the root component from the NgModule as shown in the below example.

Example: app/main.ts

NgModules

S No.

Syntax

Import

Description

1.

@NgModule({

Imports : ,

declarations: ,

exports: ,

providers: ,

bootstrap: })

class MyModule {}

import { NgModule } from ‘@angular/core’;

NgModule syntax is used to define a module in Angular 2.0 that contains components, directives, pipes, and providers as shown in the below example.

Example: app/Module.ts

S No.

NgModule body Syntax

Description

1.

declarations: [ AppComponent,

EmployeesComponent, DashboardComponent,

EmployeeDetailComponent],

Under the declarations syntax, we declare a list of components, directives, and pipes (separated by commas) which belong to this NgModule.

2.

imports: [ BrowserModule,

FormsModule, routing],

Under the imports syntax, we specify a list of modules (separated by commas) which are required to be imported into this NgModule. This is to be noted that whatever modules we are importing here, all of these will be available to declarations of this NgModule.

3.

exports: [ EmployeesComponent,

DashboardComponent,

EmployeeDetailComponent],

Under the exports syntax, we specify a list of components, directives, and pipes (separated by commas) which are visible to modules that import this NgModule.

4.

providers: [EmployeeService],

Under the providers syntax, we specify a list of dependency injection providers (separated by commas) which are visible both to the contents of this NgModule and to importers of this NgModule.

5.

bootstrap: [ AppComponent ]

Under the bootstrap syntax, we specify a list of components (separated by commas) to bootstrap when this NgModule is bootstrapped.

Built-in directives
The built-in directives require the following import in Angular 2.0.

S No.

Built-in directives

Description

1.

<section *ngIf=”selectedEmployee”>

*ngIf is used either to remove or recreate a portion of the DOM tree based on the selectedEmployee expression as shown in the below example.

2.

<li *ngFor=”let employee of employees”>

This syntax is used to turn the li element and its associated contents into a template. It uses them to instantiate a view for each item present in the employees list as shown in the example below.

3.

<div [ngSwitch]=”condExpression”>

<template [ngSwitchCase]=”case1Expression”>…</template>

<template ngSwitchCase=”case2LiteralString”>…</template>

<template ngSwitchDefault>…</template>

</div>

This works as a traditional switch case expression. It is used to Conditionally swap the contents of the div by the selection of one of the embedded templates based on the current value of condExpression.

4.

<div [ngClass]=”{active: isActive, disabled: isDisabled}”>

This syntax is used to bind the presence of CSS classes on the element to the validation of the related map values. Here, the expression at the right-hand side should return {class-name: true/false} map.

Example: resource/employees.component.html

Forms
The forms require the following import in Angular 2.0.

S No.

Forms

Description

1.

<input [(ngModel)]=”employee.name” placeholder=”name” />

This syntax provides the two-way data-binding, parsing, and validation for the form controls as shown in the below example.

Example: resource/employee-detail.component.html

Template syntaxes
The following are the Angular 2.0 template syntaxes.

S No.

Template Syntax

Description

1.

<input [value]=”name”>

This syntax is used to bind the property value to the result of expression ‘name’.

2.

<div [attribute.role]=”myRole”>

This syntax is used to bind the attribute role to the result of expression ‘myRole’.

3.

<div [class.extra-glare]=” isPleasant”>

This syntax is used to bind the presence of the CSS class extra-glare on the element to the presence of the expression isPleasant.

4.

<div [style.height.px]=”mySize”>

This syntax is used to bind the style property height to the result of expression mySize in terms of pixels. Here units are optional.

5.

<button (click)=”getEmployees ($event)”>

This syntax is used to call the method getEmployees when this button is clicked. It will trigger a click event which will be passed as the event object to the method.

6.

<div title=”Hi {{userName}}”>

This syntax is used to bind a property to an inserted string, E.g., “Hi Appy” is equivalent to: <div [title] =” ‘Hi’ + userName”>.

7.

<p>Hi {{ userName }}</p>

This syntax is used to bind a text content to an inserted string, E.g., “Hi Appy”.

8.

<my-cmp [(title)]=”companyName”>

This syntax is used to set up two-way data binding. Therefore, it is equivalent to:

<my-cmp [title]=” companyName” (titleChange)=”companyName =$event”>

9.

<video #playmovie …>

<button (click)=” playmovie.play()”>

</video>

This syntax creates a local variable playmovie which provides access to the video element instance in event-binding and data-binding expressions for the current template.

10.

<p *myUnless=”ourExp”>…</p>

When we use the * symbol then it turns the current element into an embedded template. Therefore the given syntax will be equivalent to: <template [myUnless]=”ourExp”><p>…</p></template>

11.

<p>Card No.: {{cardID | myCardIDFormatter}}</p>

This syntax is used to transform the current value of expression cardID through the use of the pipe called here as myCardIDFormatter.

12.

<p>Employer: {{employer?.cmpName}}</p>

Here (?) is known as the safe navigation operator. It means that the employer field here is an optional filed. Therefore, if it is undefined then the rest of the expression will be ignored.

13.

<svg:rect x=”0″ y=”0″ width=”400″ height=”400″/>

An SVG snippet template needs a svg: prefix on its root element in order to disambiguate the SVG element from an HTML component.

14.

<svg>

<rect x=”0″ y=”0″ width=”400″ height=”400″/>

</svg>

It is used to demonstrate that an <svg> root element can be detected as an SVG element mechanically, without the prefix.

Class Decorators
The class decorators require the following import in Angular 2.0.

S No.

Class Decorators

Description

1.

@Component ({…})

class MyAppComponent() {}

It is used to declare that a class is a component which provides the metadata about the component.

2.

@Directive ({…})

class MyAppDirective() {}

It is used to declare that a class is a directive which provides the metadata about the directive.

3.

@Pipe ({…})

class MyAppPipe() {}

It is used to declare that a class is a pipe which provides the metadata about the pipe.

4.

@Injectable()

export class EmployeeService {}

It is used to declare that a class has dependencies that should be injected into the constructor during the creation of an instance of this class by the dependency injector as shown in the below example.

Example: app/employee.service.ts

Directive configuration

S No.

Directive configuration

Description

1.

selector: ‘.fancy-button:not(a)’

It specifies a CSS selector which identifies this directive within a template. The supported selectors include element, [attribute], .class, and: not (). This is to be noted that it does not support parent-child relationship selectors.

2.

providers: [MyAppService, { provide: … }]

It specifies a list of dependency injection providers for this directive and its associated children.

Component configuration

S No.

Component configuration

Description

1.

moduleId: module.id

If this configuration is set, then the templateUrl and styleUrl are resolved by relative path to the component.

2.

viewProviders: [MyAppService, { provide: … }]

It specifies a list of dependency injection providers which are scoped to this component’s view.

3.

template: ‘Hi {{userName}}’

templateUrl: ‘my-app-component.html’

It specifies an Inline template or external template URL of the component’s view as shown in below example.

4.

styles: [‘.primary {color: blue}’]

styleUrls: [‘my-app-component.css’]

It specifies a list of inline CSS styles or the external stylesheet URLs which are used for the styling the component’s view as shown in the below example.

Example: app/employee.component.ts

Class field decorators for directives and components
The following are the Class field decorators for directives and components

S No.

Class field decorators for directives and components

Description

1.

@Input() employee: Employee;

This class field decorator is used to declare an input property that we can update via property binding. E.g., <my-cmp [employee] = “getEmployeeDetail”>.

2.

@Output() myAppEvent = new EventEmitter();

This class field decorator is used to declare an output property that could fire events which we can subscribe to with an event binding. E.g., <my-cmp (myAppEvent)=”getEmployee ()”>).

3.

@HostBinding(‘[class.validStyle]’) isValidExp;

This decorator is used to bind a host element property (i.e. the CSS class validStyle) to a directive/component property (isValidExp).

4.

@HostListener (‘click’, [‘$event’]) onClick (e) {…}

This decorator is used to subscribe to a host element event (click) with a directive/component method (onClick), which can optionally pass an argument ($event).

5.

@ContentChild (myResult) myAppChildComponent;

This decorator is used to bind the first result of the component content query (myResult) to a property (myAppChildComponent) of the class.

6.

@ContentChildren (myResult) myAppChildComponents;

This decorator is used to bind the results of the component content query (myResult) to a property (myAppChildComponents) of the class.

7.

@ViewChild(myResult) myAppChildComponent;

This decorator is used to bind the first result of the component view query (myResult) to a property (myAppChildComponent) of the class. It is not available for directives.

8.

@ViewChildren(myResult) myAppChildComponents;

This decorator is used to bind the results of the component view query (myResult) to a property (myAppChildComponents) of the class. It is not available for directives.

Directive and component change detection and lifecycle hooks
The following are the directive and component change detection and lifecycle hooks

S No.

Directive and component change detection and lifecycle hooks

Description

1.

Constructor (myAppService: MyAppService,) { … }

It is called before any other lifecycle hook. It can be used to inject dependencies, but not recommended for any severe work.

2.

ngOnChanges (changeRecord) { … }

It is called after every change to the input properties, and before processing child views or content.

3.

ngOnInit() { … }

It is called after the constructor call, initializing input properties call, and the first call to ngOnChanges.

4.

ngDoCheck() { … }

It is called every time when the input properties of a component or a directive are checked. It can be used to extend change detection by performing a custom check.

5.

ngAfterContentInit() { … }

It is called after ngOnInit when the component’s or directive’s content has been initialized.

6.

ngAfterContentChecked() { … }

It is called after every check of the component’s or directives content.

7.

ngAfterViewInit() { … }

It is called after ngAfterContentInit when the component’s view has been initialized. It is applicable to components only.

8.

ngAfterViewChecked() { … }

It is called after every check of the component’s view. It is applicable to components only.

9.

ngOnDestroy() { … }

It is called once, before the class’s instance is destroyed.

Dependency Injection configuration
The following are the dependency injection configuration details.

S No.

Dependency Injection configuration

Description

1.

{ provide: MyAppService, useClass: MyAppMockService }

This type of configuration is used to set or override the provider for MyAppService to the MyAppMockService class.

2.

{ provide: MyAppService, useFactory: myAppFactory }

This type of configuration is used to set or override the provider for MyAppService to the myAppFactory factory function.

3.

{ provide: MyAppValue, useValue: 786 }

This type of configuration is used to set or override the provider for MyAppValue to the value 786.

Routing and navigation
The routing and navigation require the following import in Angular 2.0.

S No.

Routing and navigation

Description

1.

const routes: Routes = [

{ path: ”, component: EmployeesComponent },

{ path: ‘path/:routeParam’, component: MyAppComponent },

{ path: ‘staticPath’, component: … },

{ path: ‘**’, component: … },

{ path: ‘oldPath’, redirectTo: ‘/dashboard’},

{ path: …, component: …,

data: { message: ‘Custom’ } }

]);

const routing = RouterModule.forRoot (routes);

The set up at the left-hand side is used to configure the routes for the Angular 2.0 application. It supports static, redirect, parameterized, and wildcard routes. It is also known to support custom route data and resolve.

Example: app/app.routing.ts

Conclusion
In this chapter, we have discussed in detail the cheat sheet for Angular 2.0. We have covered almost all the most frequently used syntaxes for bootstrapping, NgModules, built-in directives, forms, template syntax and their associated configuration and decorators, along with possible demo examples.

LEAVE A REPLY

Please enter your comment!
Please enter your name here