Code with Angular

Pankaj Parkar

Reach out to me

 

Email: parkarpankaj3@gmail.com

Twitter: @pankajparkar

FB: fb.com/pankaj.parkar

LinkedIn: https://in.linkedin.com/in/pankajparkar

Backround

  • Around 5 years back JS wasn't much used on client side
  • XMLHttpRequestRequest has been invented Microsoft Outlook web Access devs and came out around June 2002
  • Aug 2006 jQuery came and implement $.ajax wrapper around XMLHttpRequest
  • July-2010 Knockout came and Backbone on oct-2010 
  • Knockout and backbone solved data binding problems but upto some extend.
  • What was pitfalls with BackBone & KnockOut?

Key Problems

Data binding & code mentainability

What key problem Angular solved

  • Smooth data binding  (one way/two way)
  • Reusable, modular code
  • Came up with dependency Injection which made code more testable.

Things you should know before we start..

  • DOM
  • Imperative and Declarative way of code.
  • Decorators / Annotations

DOM (Document Object Model)

  • Window is Global Object
  • Each node of html is DOM, even window(global) object is considered as DOM
<p align="right">
    Content
</p>
document.querySelector('p')

Imperative Programming

what to do, not how to do it

var numbers = [1,2,3,4,5]
var total = 0

for(var i = 0; i < numbers.length; i++) {
  total += numbers[i]
}
console.log(total) //=> 15

Calculate Sum

Get odd number collection

Declarative Programming

var results = collection.Where( 
    num => num % 2 != 0
);

What you want.

Get odd number collection

Calculate Sum

var results = collection.Sum(
    x => x
)

Imperative vs Declarative

<label>Username</label>
<input type="text" id="username" class="username" />

<label>Password</label>
<input type="password" id="password" class="password" />

<button onclick="submit()"> Login </button>
$("#username").on('keyup', function(event){
    var value = event.target.value;
    //Some awesome logic 
    if(valid) 
       //remove disable attribute from button
    else 
       //add disable attribute for button
});

$('#password').on('keyup', function(event){
    var value = event.target.value;
    //Some awesome logic 
    if(valid) 
       //remove disable attribute from button
    else 
       //add disable attribute for button
});

$('#form').submit(submit);
function submit(){
   //check form validity
   //submit form date to server if valid
};

This code is imperative code which goes on increasing as number of field will be increased

Login Form

Imperative vs Declarative

<form name="loginForm" ng-submit="submit(model)">
    <label>Username</label>
    <input type="text" ng-pattern="/^[a-zA-Z]$/" class="username" ng-model="model.userName"/>
    
    <label>Password</label>
    <input type="password" id="password" class="password" ng-model="model.password"/>
    
    <button ng-disabled="loginForm.invalid"> Login </button>
</form>

We used declarative approach to made form working.

Decorators

  • Basically it is declarative way of doing code.
  • It is same as that of Annotation in OOP language like @HttpGet, [HttpPost], etc.

Official Terms

Angular 1.X => AngularJS

Angular 2+ => Angular

What is Angular? 

  • Framework supported on all platform

  • Superfast 

  • Incredible tooling

  • Great community support.

Why Angular?

  • Dependency Injection

  • Two way data bindings

  • Forms

  • Server side rendering

  • AOT (Ahead Of Time Compilation)

  • Modular & Testable code

  • 5x faster than AngularJS

  • Component Architecture

  • Single Framework for everything

Component

  • It is basic building block of an Angular application

  • It meant to server single purpose

  • Gmail / Google example

@Component({
   selector: 'greet', 
   template: 'Hello {{name}}!',
   //templateUrl: '/path/to/template.html'
   styles: ['.app { display: block }'],
   providers: [],
   styleUrls: ['/app/path/to.css']
})
export class GreetComopnent {
  name: string = 'World';
}

Component(checklist)

  • Inject it inside NgModule `declarations` metadata option

  • Main component should be injected inside bootstrap of your application

  • Component class should be exported to use it in module.

NgModule

  • Used to modularize Angular application

  • It help organize an application into cohesive blocks of functionality.

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

@NgModule({
  imports:      [ BrowserModule ], //other modules
  declarations: [ AppComponent ], //components, directives, pipes
  bootstrap:    [ AppComponent ] //bootstrap component
})
export class AppModule { }

NgModule(checklist)

  • Class should be exported

  • All metadata options should be filled correctly

Architecture

AppModule

Service

Comp1

Comp3

Pipe

Sub Module

Router

In general router responsible for perform action based on url pattern provided it.

<body>
    my-html-content

    ....
 
    <some-placeholder></some-placeholder>


    ..Other html
</body>
{
    'pattern': '/my-path', action: 'doSomething',
    'pattern': '/my-path-2', action: 'doSomethingElse',
    ...
}

Config

Router

Two ways to write configure router 

  • Eager loading

  • Lazy loading

Router(checklist)

  • Make sure, you have loaded RouterModule inside your application

  • Register routes before importing module

Bindings

Data Bindings

{{myData}}

 

Property Binding 

[myData]="test"

 

Event Binding

(eventName)="methodCall($event)"

What is RestFul service & JSON

HttpModule

  • To get data from server like we do ajax to communicate with data 
  • To use this module just Import the HttpModule inside your AppModule

Dependency Injection

Sync vs Async

Pizza order example

  • Sync way
  • Async

Dependent code execution which should to fetch response from API before proceed to next function.

  • Suppose I have to process 10 task, they should get process synchronously one after the other

Sync vs Async(callbacks)

function errorFn(error){ console.log(error) }
task1(function successFn(data){
    console.log(data);
    task2(function successFn(){
        task3(function successFn(){
            task4(function successFn(data){
                console.log(data);
                task5(function successFn(){
                    task6(function successFn(){
                        task7(function successFn(data){
                            console.log(data);
                            task8(function successFn(){
                                task9(function successFn(){
                                    task10(function successFn(data){
                                        console.log(data);
                                        console.log("We're done");
                                    }, errorFn)
                                }, errorFn)
                            }, errorFn)
                        }, errorFn)
                    }, errorFn)
                }, errorFn)
            }, errorFn)
        }, errorFn)
    }, errorFn)
}, errorFn)

Sync vs Async(promise)

function errorFn(error){ 
    console.log(error) 
}
function successFn(data){ 
    console.log(data); 
    return data; 
}
task1(task2Fn,errorFn)
.then(task3Fn, errorFn)
.then(task4Fn, errorFn)
.then(task5Fn, errorFn)
.then(task6Fn, errorFn)
.then(task7Fn, errorFn)
.then(task8Fn, errorFn)
.then(task9Fn, errorFn)
.then(task10Fn, errorFn)

Array

var items = [1, 2 , 3, 4];

//add them

var result = 0;
items.forEach(function(item){
   result += item;
});

console.log('Total', result);
  • Collection of elements
  • You can use various method over it, like map, filter, reduce, etc.

Observable

  • Everything is reactive
  • This generally follows pub sub pattern

Observable

Listner

Listner

Stream

Stream

Observable

Observable(array)

Listner

Listner

Stream

Stream

[1, 2, 3, 4]

push 5, 6

Service

  • It is service purpose sharing data.
  • This can be shared in application common data.
@Injectable() //< --this is important part
export class GreetService {
  name: string = 'World';
  sendSomeMessage(){
    console.log("Hello world ", this.name)
  }
}

Service

  • It should be injected inside providers of `NgModule`

Pipe

  • Show some human readable value on html instead of what we have got from API.
  • When & how to use it?

Pipe(checklist)

  • It should be included in declarations array of your App Module NgModule metadata options

Lifecycle Hooks

1

2

2

3

last

Change Detection

Component to Component interaction

  • @Input & @Output decorators.

Child route

  • How to specify children routes.
  • How to navigate to them
  • routerLink directive

  • router.navigate method

Forms

  • Basics form concepts first
  • Pristine
  • dirty
  • valid/invalid
  • touched/untouched
  • How difficult it could be using jQuery(you could consider removing this point?)

Forms

Forms API made form validation super easy in Angular

Two Types of Form

  • Template Driven

  • Model driven

 

When to use what?

How to use third party library in Angular?

  • 3rd party library without typescript implementation(Toastr)

  • Some other third party library

Modularize application with multiple NgModule

Bundling and minifications

Reference

Angular Good Blogs

http://thoughtram.io/
johnpapa.net
toddmotto.com
https://teropa.info
angular.io
https://netbasal.com/@NetanelBasal
https://medium.com/@maximus.koretskyi

Docs

https://angular.io/docs
https://angular.io/api (For API import check)

Best Practices

Coding guidelines by John Papa https://angular.io/guide/styleguide

Books
https://angular-2-training-book.rangle.io/
https://codecraft.tv/courses/angular/

Github Repository

https://github.com/pankajparkar/bug-tracker

(do click star button there, if you like it)

Q & A

Thank You

Made with Slides.com