Angular cheat sheet

A cheat sheet for you to learn and use Angular. 

Bootstrapping an application using AppComponent 

  • index.html – The single html file which first gets loaded for any single page application.This should include the selector of the primary component (AppComponent)
<body>
<app-root>Loading...</app-root>
</body>
  • main.ts – The main entry point of the application and the first file to get executed is the main.ts where the bootstrap module is set as the AppModule
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
  •  app.module.ts – The AppModule, which is the bootstrap module, is defined in the app.module.ts file. This module is the primary module which is defined in every application. Other modules may be added in case of complex applications but any application will surely have the AppModule. Here the bootstrap component is defined as AppComponent.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
bootstrap: [AppComponent]
})
export class AppModule { }

 

Defining Components

app.component.ts – The first component to be defined. This will include all the other components, providers and directives to be used in the application.

import { Component, ViewEncapsulation } from '@angular/core';
/*
* App Component
* Top Level Component
*/
@Component({
selector: 'app-root',
encapsulation: ViewEncapsulation.None,
styleUrls: [
'./app.style.css'
],
template: `
<main>
<router-outlet></router-outlet>
</main>
`
})
export class AppComponent {
constructor() {
}
ngOnInit() {
//To handle initialization activities
}
}

login.component.ts A new component to be included for the application. Every new component will have its own folder with ts and html file. The css can also be defined separately or in the ts definition itself.  Similarly different components can be defined for the application. These should be included in the app.module.ts under declarations to be used by the application.

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@Component({
selector: 'login',
templateUrl: './login.component.html'
})

export class Login {
public _email: string;
public _password: string;
constructor() {
}

ngOnInit() {
}
login() {
//code to handle the event
}
}

 login.component.html – The template for the new component which defines the view part of the component.

 <body>Welcome to Login Page</body>

 

 

Routing

index.html – Add a <base> element to the index.html as the first child in the <head> tag to tell the router how to start composing the navigation URLs.

<head>
<base href="/">
</head>

app-routing.module.ts – Define the routes in the routing module.

import { NgModule } from '@angular/core';
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
//import the required components
export const appRoutes: Routes = [
{ path: '', redirectTo: '/allstories', pathMatch: 'full' }, 
// default route using redirectTo
{ path: 'allstories', component: Allstories' },
{ path: 'login', component: Login},
{ path: '*', component: NoSite } 
// If no route matches, wild card or error route
];
export const appRoutingProviders: any[] = [
];
export const routing: ModuleWithProviders = 
RouterModule.forRoot(appRoutes);
@NgModule({
imports: [RouterModule.forRoot(appRoutes,{useHash: false})],
exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts – The routing module to be imported and used in AppModule.

import { AppRoutingModule,
appRoutingProviders } from './app.routing';
//Include the AppRoutingModule in the imports for the Module
@NgModule({
declarations: [
AppComponent,
Login,
Allstories],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [
UserService,
appRoutingProviders],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts – Inclusion of navigation in app.component.ts and anchor tag to include the link for navigation

import { Component, ViewEncapsulation } from '@angular/core';
import { Router, Event, NavigationEnd } from '@angular/router';
/*
* App Component
* Top Level Component
*/
@Component({
selector: 'app-root',
encapsulation: ViewEncapsulation.None,
styleUrls: [
'./app.style.css'
],
template: `
<main>
<a routerLink="/register">Register</a>
<router-outlet></router-outlet>
</main>
`
})
export class AppComponent {
constructor( public router: Router) {
}
ngOnInit() {
}
}

login.component.ts – Navigate from one page to another in .ts code shown in login.component.ts to navigate to allstories page as defined in the routes

import { Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Router, ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'login',
templateUrl: './login.component.html'
})
export class Login {
public _email: string;
public _password: string;
constructor(public _router: Router) {
}
ngOnInit() {
let email = localStorage.getItem("email");
let password = localStorage.getItem("password");
if (email != undefined && email != "" && password != undefined 
&& password != "") {
this._router.navigate(['/allstories']);
}
}
}

Binding

Interpolation {{expression}}

One Way binding from data source in component.ts to be displayed in the component.html view

@Component({
selector: 'app-root',
template: ` {{title}} `
})
export class MyComponent {
public title ='Binding in Angular';
constructor() {
}
}

Template expressions [property]=”expression”

A template expression produces a value which is assigned to a property of a binding target; the target might be an HTML element, a component, or a directive.

 @Component({
selector: 'app-root',
template: `
{{title}}
<input [value]="title" type="text"> `
})
export class MyComponent {
public title ='Binding in Angular';
constructor() {
}
}

Event handling (event)=”statement”

One-way from view target event to data source handler.

@Component({
selector: 'app-root',
template: `
{{title}}
<input [value]="title" type="text">
<button class="ui inverted blue button" (click)="buttonclick()">
Take the test</button> `
})
export class MyComponent {
public title ='Binding in Angular';
constructor() {
}
buttonclick(){
alert('Event handler for button - test taken');
}
}


Two way binding [(ngModel)]=”name”

Two way binding between the data source and view target where change in either changes the other.

@Component({ 
selector: 'app-root', 
template: ` {{title}} 
<input [value]="title" type="text">  
<input type="text" [(ngModel)]="title"> 
<button class="ui inverted blue button" (click)="buttonclick()">
Take the test</button> ` 
})
export class MyComponent { 
public title ='Binding in Angular'; 
constructor() {
 }
 buttonclick(){ 
   alert('Event handler for button - test taken');
 }
 } 

 

Services and Dependency Injection handled by HTTP

user.service.ts – Define the service using the @Injectable decorator

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';

@Injectable()
export class UserService {
public userData: any;
public url: string = 'http://localhost:9000/';
 // the server url handling data requests

constructor(public _http: Http) {
}
getUserDetails(userId) {
this.userData= this._http.get(this.url + 'userprofile/' + userId)
.map(res => res.json());
return this.promise;
}
}

app.module.ts – Include in providers in app.module.ts to be included and used anywhere in the application

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { UserService } from './service/user.service';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
UserService],
bootstrap: [AppComponent]
})
export class AppModule { }

Concluding Thoughts

I hope this cheat sheet will help you to get started with Angular and will come handy to refer for the common syntax usage in Angular.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s