Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Learn how to create a cheat sheet for Angular 2


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

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './Module';
platformBrowserDynamic().bootstrapModule(AppModule);

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

import { NgModule }       from '@angular/core';
import { BrowserModule }  from '@angular/platform-browser';
import { FormsModule }    from '@angular/forms';
import { AppComponent }   from './app.component';
import { EmployeesComponent }  from './employees.component';
import { DashboardComponent }  from './dashboard.component';
import { EmployeeDetailComponent }  from './employee-detail.component';
import { EmployeeService }  from './employee.service';
import { routing }        from './app.routing';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    routing
  ],
  declarations: [
    AppComponent,
    EmployeesComponent,
    DashboardComponent,
    EmployeeDetailComponent
  ],
  providers: [
    EmployeeService
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

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.

import { CommonModule } from '@angular/common';

S No.

Built-in directives

Description

1.

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

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

    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.

    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

    {{title}}

    Our Employees

    • {{employee.id}} {{employee.name}}

    {{selectedEmployee.name | uppercase}} is the Best Employee.

    Forms
    The forms require the following import in Angular 2.0.

    import { FormsModule } from '@angular/forms';

    S No.

    Forms

    Description

    1.

    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

    {{employee.name}} details!

    {{employee.id}}

    Template syntaxes
    The following are the Angular 2.0 template syntaxes.

    S No.

    Template Syntax

    Description

    1.

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

    2.

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

    3.

    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.

    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.

    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.

    This syntax is used to bind a property to an inserted string, E.g., “Hi Appy” is equivalent to:

    .

    7.

    Hi {{ userName }}

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

    8.

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

    9.

    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.

    When we use the * symbol then it turns the current element into an embedded template. Therefore the given syntax will be equivalent to:

    11.

    Card No.: {{cardID | myCardIDFormatter}}

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

    12.

    Employer: {{employer?.cmpName}}

    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.

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

    14.

    It is used to demonstrate that an 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.

    import { Directive, Component, Pipe, Injectable } from '@angular/core';

    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

    import { Injectable } from '@angular/core';
    import { Employee } from './employee';
    import { EMPLOYEES } from './mock-employees';
    
    @Injectable()
    export class EmployeeService {
    
      getEmployees(): Promise {
        return Promise.resolve(EMPLOYEES);
      }
      getEmployee(id: number): Promise {
      return this.getEmployees()
                 .then(employees => employees.find(employee => employee.id === id));
    	}
    }

    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

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { Employee } from './employee';
    import { EmployeeService } from './employee.service';
    
    @Component({
      selector: 'my-employees',
      templateUrl: 'resource/employees.component.html',
      styleUrls:  ['assets/employees.component.css']
    })
    
    export class EmployeesComponent implements OnInit {
      employees: Employee[];
      selectedEmployee: Employee;
     
      constructor(
        private router: Router,
        private employeeService: EmployeeService) { }
    
      getEmployees(): void {
        this.employeeService.getEmployees().then(employees => this.employees = employees);
      }
    
      ngOnInit(): void {
        this.getEmployees();
      }
    
      onSelect(employee: Employee): void {
        this.selectedEmployee = employee;
      }
    
      gotoDetail(): void {
        this.router.navigate(['/detail', this.selectedEmployee.id]);
      }
    }

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

    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., ).

    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.

    import { Routes, RouterModule, ... } from '@angular/router';

    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

    import { Routes, RouterModule } from '@angular/router';
    import { EmployeesComponent }      from './employees.component';
    import { DashboardComponent }   from './dashboard.component';
    import { EmployeeDetailComponent }  from './employee-detail.component';
    
    const appRoutes: Routes = [
      {
        path: '',
        redirectTo: '/dashboard',
        pathMatch: 'full'
      },
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'detail/:id',
        component: EmployeeDetailComponent
      },
      {
        path: 'employees',
        component: EmployeesComponent
      }
    ];
    export const routing = RouterModule.forRoot(appRoutes);

    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.

    The post Learn how to create a cheat sheet for Angular 2 appeared first on Eduonix.com | Blog.



    This post first appeared on How And When Should You Use HBase NoSQL DB, please read the originial post: here

    Share the post

    Learn how to create a cheat sheet for Angular 2

    ×

    Subscribe to How And When Should You Use Hbase Nosql Db

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×