Angular Cheat Sheet

https://angular.io/guide/setup-local

app.module.ts

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

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AddComponent } from './add/add.component';
import { HomeComponent } from './home/home.component';

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

import { HttpClientModule } from '@angular/common/http'

@NgModule({
  declarations: [
    AppComponent,
    AddComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

if app-routing.module.ts is not present then run this in root folder
ng generate module app-routing –flat –module=app

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AddComponent } from './add/add.component';

const routes: Routes = [
  { path: 'add', component: AddComponent },
  { path: 'add/:num1/:num2', component: AddComponent },
  // { path: 'sub', component: SubComponent },
  // { path: 'mul', component: MulComponent },
  // { path: 'div', component: DivComponent },
  { path: '**', component: HomeComponent },
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }

app.component.html

<a routerLink="/"  routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a> |
<a routerLink="/add"  routerLinkActive="active">Add</a>
<router-outlet></router-outlet>

app.component.css

.active {
  background-color: beige;
}

home.component.ts

ng g c home

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms'
import { HomeService } from './home.service'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  fruits = ["Orange", "Mango", "Banana", "Apple"];

  num1: number = 0;
  square: number = 0;

  form = new FormGroup({
    num1: new FormControl(),
    num2: new FormControl()
  });
  formResult: any;

  userRecords: any;

  constructor(private service: HomeService) { }

  ngOnInit() {
  }

  getSqr() {
    var x = this.num1;
    this.square = x * x;
  }

  addNum() {
    let x = parseInt(this.form.value.num1);
    let y = parseInt(this.form.value.num2);
    this.formResult = x + y;
  }

  getUsers() {
    this.service.getData().subscribe((response) => {
      console.log(response);
      this.userRecords = response;
    })
  }

}

home.component.html

<p>home works!</p>
{{ fruits }}

<div *ngFor="let fruit of fruits">
  {{fruit}}
</div>


<input type="text" (keyup)="getSqr()" [(ngModel)]="num1"/>
<div>
  Square of {{num1}} is {{square}}
</div>


<form [formGroup]="form" (submit)="addNum()">
  <input type="text" formControlName="num1"/>
  <input type="text" formControlName="num2"/>
  {{ form.value | json }}
  <div>
    Result: {{ formResult }}
  </div>
  <input type="submit" value="Add"/>
</form>


<button (click)="getUsers()">Get Data from Json Placeholder</button>
<div>
  {{userRecords}}
  <pre>
    {{userRecords | json}}
  </pre>
</div>

home.service.ts

cd home
ng g s home

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HomeService {

  constructor(private http: HttpClient) { }

  getData() {
    let url = "https://jsonplaceholder.typicode.com/users";
    return this.http.get(url);
  }
}

add.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {

  number: number;
  param1: number;
  param2: number;

  constructor(private route: ActivatedRoute, private router: Router) {
    console.log(this.route.snapshot.url)
    console.log(this.route.snapshot.params)
    this.number = parseInt(this.route.snapshot.queryParamMap.get('id'))
    this.param1 = parseInt(this.route.snapshot.params.num1);
    this.param2 = parseInt(this.route.snapshot.params.num2);
  }

  ngOnInit() {
    console.log(this.number)
    console.log(this.param1)
    console.log(this.param2)

    // setTimeout(() => {
    //   this.router.navigate(['home']);
    // }, 3000)
  }

}
my-app\src\app\interceptor\httpconfig.interceptor.ts
import { Injectable } from '@angular/core';
import {
    HttpInterceptor,
    HttpRequest,
    HttpResponse,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token: any = localStorage.getItem('token');
        // const token: string = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1X25hbWUiOiJhZG1pbiIsInB3ZCI6IkBkbWluIiwiaWF0IjoxNjEyNjM2OTc5fQ.ehlxu7z_1HSW4bPK902nLOAZOpHtutfkJ43lCxQnL68`;
        if (token) {
            request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
        }

        if (!request.headers.has('Content-Type')) {
            request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
        }

        request = request.clone({ headers: request.headers.set('Accept', 'application/json') });

        return next.handle(request).pipe(
            map((event: HttpEvent<any>) => {
                if (event instanceof HttpResponse) {
                    console.log('event--->>>', event);
                }
                return event;
            }));
    }
}

app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RouterModule } from '@angular/router';

import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { HttpConfigInterceptor } from './interceptor/httpconfig.interceptor';


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]

})
export class AppModule { }

Angular 4 Deployment

Use any of the commands:

  1. ng build
  2. ng build –prod
  3. ng build –prod –base-href /directory-name/sub-directory-name/

Create testing branch on github

  1. add normal git repository
  2. git branch gh-pages
  3. git push -u origin gh-pages

To push on the git repository

  1. git init
  2. git add origin
  3. git add .
  4. git commit -m “Initial Commit”
  5. git push -u origin master
  6. ng build –prod –base-href https://whateveruser.github.io/whateverprojectrepo/
  7. ngh

ng build –prod –base-href https://github.com/whateveruser/whateverprojectrepo/

Ref:

  1. https://www.youtube.com/watch?v=nxV3weqMzYo

.htaccess for production site

RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

 

Filters

<DOCTYPE html>
    <html>
        <head>
            <meta CHARSET="UTF-8">
            <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        </head>
        <body ng-app="myApp" ng-controller="myCtrl">
            <h2>Filters (uppercase, lowercase, currency, filter, Custom filter)</h2>
            <fieldset>
                <legend>
                    Uppercase
                </legend>
                <div ng-init='name = {"first_name":"Shailesh"}'>
                    {{name.first_name| uppercase}}
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Lowercase
                </legend>
                <div ng-init='month = {"first":"january"}'>
                    {{month.first| lowercase}}
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Currency
                </legend>
                <div ng-init='currency = {"inr": 20000, "usd":30000, "euro": 25000}'>
                    <!-- {{ currency_expression | currency : symbol : fractionSize}} -->
                    {{currency.inr| currency : ' &#8377;' : 3}} <br/>
                    {{currency.usd| currency}} <br/>
                    {{currency.euro| currency : '&euro;'}}
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Single Filter
                </legend>
                <div ng-init='city = ["Mumbai", "Pune", "Nagpur"]'>
                    <table border="1">
                        <ul>
                            <li ng-repeat="x in city">
                                {{x}}
                            </li>
                        </ul>
                    </table>
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Multiple Filter
                </legend>
                <div>
                    Search by any <input type="text" name="" ng-model="search.$"/> <br/>
                    Search by Name <input type="text" name="" ng-model="search.name"/> <br/>
                    Search Country <input type="text" name="" ng-model="search.country"/> <br/>
                    <table border="1">
                        <tr ng-repeat="x in emp_records| filter:search">
                            <td>{{x.name}}</td>
                            <td>{{x.country}}</td>
                            <td>{{x.age}}</td>
                        </tr>
                    </table>
                </div>
            </fieldset>
            <fieldset>
                <legend>
                    Multiple Filter Skip Few
                </legend>
                <div>
                    Search by Name or Country Only <input type="text" name="" ng-model="query"/> <br/>
                    <table border="1">
                        <tr ng-repeat="x in emp_records| filter:search2">
                            <td>{{x.name}}</td>
                            <td>{{x.country}}</td>
                            <td>{{x.age}}</td>
                        </tr>
                    </table>
                </div>
            </fieldset>
        </body>
        <script>
            var app = angular.module("myApp", []);
            app.controller("myCtrl", function ($scope) {
                $scope.emp_records = [
                    {name: 'Jani', country: 'Norway', 'age': 20},
                    {name: 'Carl', country: 'Sweden', 'age': 21},
                    {name: 'Margareth', country: 'England', 'age': 22},
                    {name: 'Hege', country: 'Norway', 'age': 23},
                    {name: 'Joe', country: 'Denmark', 'age': 24},
                    {name: 'Gustav', country: 'Sweden', 'age': 25},
                    {name: 'Birgit', country: 'Denmark', 'age': 26},
                    {name: 'Mary', country: 'England', 'age': 27},
                    {name: 'Kai', country: 'Norway', 'age': 28}
                ];

                $scope.search2 = function (row) {
                    return (angular.lowercase(row.name).indexOf(angular.lowercase($scope.query) || '') !== -1 ||
                            angular.lowercase(row.country).indexOf(angular.lowercase($scope.query) || '') !== -1);
                };
            });

        </script>
    </html>

 

ng-repeat

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <h2>ng-repeat</h2>
        <fieldset>
            <legend>
                List
            </legend>
            <div ng-init='name = ["Shailesh", "Mahesh", "Shilpa"]'>
                <ul>
                    <li ng-repeat="x in name">{{x}}</li>
                </ul>
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Table
            </legend>
            <div ng-init='months = ["Jan", "Feb", "Mar"]'>
                <table border="1">
                    <tr ng-repeat="x in months">
                        <td>{{x}}</td>
                    </tr>
                </table>
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Select
            </legend>
            <div ng-init='cities = [{"id":"1", "value":"Mumbai"}, {"id":"2", "value":"Pune"}, {"id":"3", "value":"Nagpur"}]'>
                <select>
                    <option ng-repeat="x in cities" value="{{x.id}}">{{x.value}}</option>
                </select>
            </div>
        </fieldset>
    </body>
    <script>
                var app = angular.module("myApp", []);
                app.controller("myCtrl", function($scope) {

                });
    </script>
</html>

 

 

Working with JSON

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <h2>JSON</h2>
        <fieldset>
            <legend>
                String
            </legend>
            <div ng-init='name = {"first_name":"Shailesh", "last_name" : "Sonare"}'>
                {{name.first_name}} <br/>
                {{name.last_name}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Numbers
            </legend>
            <div ng-init='months = {"jan": 1, "feb" : 2}'>
                {{months.jan}} <br/>
                {{months.feb}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Objecs
            </legend>
            <div ng-init='result = {employee:{"name": "Shailesh", "age" : 28}}'>
                {{result.employee.name}} <br/>
                {{result.employee.age}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Array
            </legend>
            <div ng-init='result = {employee:[{"name": "Shailesh", "age" : 28},{"name": "Mahesh", "age" : 26}]}'>
                {{result.employee[0].name}} <br/>
                {{result.employee[1].age}}
            </div>
            <div ng-init='result2 = {months:["Jan","Feb"]}'>
                {{result2.months[0]}} <br/>
                {{result2.months[1]}}
            </div>
        </fieldset>
    </body>
    <script>
        var app = angular.module("myApp", []);
        app.controller("myCtrl", function($scope) {

        });
    </script>
</html>

 

 

Routing without hashtag

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <base href="/">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
    </head>
    <body ng-app="myApp">
        <aside>
            <a href="testlab/angular/sample/26_routing_without_hashing.html">Home</a>
            <a href="red">Red</a>
            <a href="green">Green</a>
            <a href="blue">Blue</a>
            <a href="default">Default</a>
        </aside>
        <section ng-view></section>
    </body>
    <script>
        var app = angular.module("myApp", ["ngRoute"]);
        app.config(function ($routeProvider, $locationProvider) {
            $routeProvider
                    .when("/red", {
                        template: "<h2 style='color:red;'>Red Color</h2>"
                                /*
                                 templateUrl : "red.html",
                                 controller : "myCtrl"
                                 */
                    })
                    .when("/green", {
                        template: "<h2 style='color:green;'>Green Color</h2>"
                    })
                    .when("/blue", {
                        template: "<h2 style='color:blue;'>Blue Color</h2>"
                    })
                    .otherwise({
                        template: "<h2>Default Black Color</h2>"
                    });

            $locationProvider.html5Mode(true);
        });
    </script>
</html>

 

 

Routing

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
    </head>
    <body ng-app="myApp">
        <aside>
            <a href="#red">Red</a>
            <a href="#green">Green</a>
            <a href="#blue">Blue</a>
            <a href="#default">Default</a>
        </aside>
        <section ng-view></section>
    </body>
    <script>
        var app = angular.module("myApp", ["ngRoute"]); // where ngRoute is a dependent module
        app.config(function ($routeProvider) {
            $routeProvider
                    .when("/red", {
                        template: "<h2 style='color:red;'>Red Color</h2>"
                    })
                    .when("/green", {
                        template: "<h2 style='color:green;'>Green Color</h2>"
                    })
                    .when("/blue", {
                        template: "<h2 style='color:blue;'>Blue Color</h2>"
                    })
                    .otherwise({
                        template: "<h2>Default Black Color</h2>"
                    });
        });
    </script>
</html>

 

 

Services

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <h2>Scope</h2>
        <fieldset>
            <legend>
                Location
            </legend>
            <div>
                Absolute URL {{current_url}} <br/>
                Protocol {{protocol}} <br/>
                Port {{port}} <br/>
                Host {{host}} <br/>
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Timeout
            </legend>
            <div>
                {{greeting}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Time Interval
            </legend>
            <div>
                {{counter}}
            </div>
        </fieldset>
        <fieldset>
            <legend>
                Custom Service
            </legend>
            <div>
                Square of 5 is {{square}} <br/>
                Cube of 5 is {{cube}} <br/>
            </div>
        </fieldset>
        <fieldset>
            <legend>
                HTTP Service
            </legend>
            <div>
                {{ajax_response}}
            </div>
        </fieldset>
    </body>
    <script>
        var app = angular.module("myApp", []);

        app.service('square_cube', function () {
            this.square = function (x) {
                return x * x;
            }

            this.cube = function (x) {
                return x * x * x;
            }
        });

        app.controller("myCtrl", function ($scope, $location, $timeout, $interval, square_cube, $http) {

            $scope.current_url = $location.absUrl();
            $scope.protocol = $location.protocol();
            $scope.port = $location.port();
            $scope.host = $location.host();

            $timeout(function () {
                $scope.greeting = "Hello India"
            }, 5000);

            $scope.counter = 0;

            $interval(function () {
                $scope.counter = $scope.counter + 1;
            }, 1000);

            $scope.square = square_cube.square(5);
            $scope.cube = square_cube.cube(5);

            $http.get('ajax_response.html').then(function (response) {
                $scope.ajax_response = response.data[1].name;
            });

        });
    </script>
</html>

 

 

Scope

 

<DOCTYPE html>
<html>
    <head>
        <meta CHARSET="UTF-8">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp">
        <h2>Scope</h2>
        <fieldset>
            <legend>
                Circle
            </legend>
            <div ng-controller="Circle">
                Radius = {{radius}} <br/>
                Diameter = {{diameter}} <br/>
                Area = {{area}} <br/>
                Circumference = {{circumference| number:2}} <br/>
            </div>
            {{globalMessage}}
        </fieldset>
        <fieldset>
            <legend>
                Root Scope
            </legend>
            <div>
                {{globalMessage}}
            </div>
        </fieldset>
    </body>
    <script>
        var app = angular.module("myApp", []);

        app.run(function ($rootScope) {
            $rootScope.globalMessage = "I am from root Scope available throughout the module";
        });

        app.controller("Circle", function ($scope) {
            $scope.radius = 5;
            $scope.diameter = $scope.radius * 2;
            $scope.area = 3.14 * $scope.radius * $scope.radius;
            $scope.circumference = 2 * 3.14 * $scope.radius;
        });
    </script>
</html>