Angular Fundamentals

Introduction to Angular, Google's flagship framework for Browser, Desktop and Mobile

$ whoami

$ whoami

Let's talk something about you

What is 

?

Superheroic MVW Framework

1.x

1.x

20th October, 2010

First Stable

Today

v1.6.4

Sept 2015 May 2016 Sept 2016 Apr 2017
1.2 M 1.3 M 1.3 M 1.3 M

One framework. Mobile & Desktop

2 and beyond

2 and beyond

15th Sep, 2016

2.0.0

Today

v4.1.0

Sept 2015 May 2016 Sept 2016 Apr 2017
85 k 450 K 645 K 810 K
  • Angular 2 onwards is a complete rewrite of the framework
  • It has made great architectural choices
  • Written in Typescript
  • Fast and small, becoming faster and smaller
  • Works across platforms (browser, desktop and mobile)
  • Gentler learning curve as compared to 1.x

What is a Single Page Application?

  • Separation of concerns
  • Excellent UX
  • Faster

Architecture

Modules

Components

Directives

Routing

Services

Modules

Modules are the basic building blocks that contain components, directives, services etc

Chat

Inbox

Search

Simplified GMail Interface

C

D

R

S

C

D

R

S

C

D

R

S

Components

Components contain your template which translates into the DOM nodes on the view. It also contains logic

C

C

C

C

C

C

C

Root Component

Directives

Directives can be attached to existing components or HTML elements to attach, extend and transform their behavior 

C

C

C

C

C

C

C

Root Component

D

Services

Services is where the data comes from. It also hosts the logic which isn't related to the component

C

C

C

C

C

C

C

Root Component

D

S

Routing

Renders the Components based on the url on the address bar. It also controls the navigation.

C

C

C

C

C

C

Root Component

D

S

R

Primer on ES6

Definition

//ES6
class Shape {
    constructor (id, x, y) {
        this.id = id
        this.move(x, y)
    }
    move (x, y) {
        this.x = x
        this.y = y
    }
}
//ES5
var Shape = function (id, x, y) {
    this.id = id;
    this.move(x, y);
};
Shape.prototype.move = function (x, y) {
    this.x = x;
    this.y = y;
};

Class

Next

Inheritance

//ES6
class Rectangle extends Shape {
    constructor (id, x, y, width, height) {
        super(id, x, y)
        this.width  = width
        this.height = height
    }
}
class Circle extends Shape {
    constructor (id, x, y, radius) {
        super(id, x, y)
        this.radius = radius
    }
}
//ES5
var Rectangle = function (id, x, y, width, height) {
    Shape.call(this, id, x, y);
    this.width  = width;
    this.height = height;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var Circle = function (id, x, y, radius) {
    Shape.call(this, id, x, y);
    this.radius = radius;
};
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;

Class

Next

//ES6
(function(){
    
    /**
        let/const keywords are block scoped
        i.e. name will only be accessible
        inside the if block
    */
    if(true){
        var name = 'Bruce Wayne';
    }

    /**
        let/const keywords don't allow 
        variables to leak outside their 
        block
    */
    
    console.log(name); //prints 'undefined'

}());
//ES5
(function(){
    
    /**
        Javascript hoists var name up top
        and name is assigned when line is
        executed
    */
    if(true){
        var name = 'Bruce Wayne';
    }

    /**
        var is function scope hence variable
        name is available in print
    */
    
    console.log(name); //prints 'Bruce Wayne'

}());

Blocked scope vars

//ES6

/**
    Arrow functions are concise and
    implicitly return value
*/
[1,2,3].map(val => val * 2); // [2, 4, 6]

/**
    Automatically binds the lexical this
*/
this.name = 'Bruce Wayne';
[1,2,3].forEach(val => {
    console.log(this.name, val)
});
//ES5

/**
    Normal functions have a 
    slightly longer syntax
*/
[1,2,3].map(function(val){
    return val * 2;
}); // [2, 4, 6]

/**
    Normal functions don't
    bind the lexical this
*/
var self = this;
self.name = 'Bruce Wayne';
[1,2,3].forEach(function(val) {
    console.log(self.name, val)
});

Arrow Functions

//ES6

/**
    String interpolation
*/
let firstName = 'Bruce';
console.log(`Hello ${firstName}`)


/**
    Multi-line strings
*/
let address = `
    In the middle of Nowhere!
`;
console.log(address);
//ES5

/**
    String concatenation
*/
var firstName = 'Bruce';
console.log('Hello ' + firstName);


/**
    Multi-line strings
*/
var address = '\nIn the middle of Nowhere!\n';
console.log(address);

Template Literals

//ES6

///firstFile.js

export class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

///secondFile.js

import { foo, Person } from './firstFile';

const batman = new Person('Bruce Wayne', 40);

Modules

Typescript

Typescript

Typescript

Typescript

Javascript

No runtime required

Types

Optional Type annotations

You screwed up !

// Javascript
...
var username = 'brucewayne@wayneenterprises.com';
username.toLowerCase().find('@');
...
// Typescript
...
let username: string = 'brucewayne@wayneenterprises.com';
username.toLowerCase().find('@');
...

Types

  • number
  • string
  • boolean
  • array
  • any
  • custom
var age = 5;
var name = true;
var address = 'neverland';
var numbers = [1,2,3,4];
var counting = [1,2,3,4];
var tuple = [1, 'batman'];
var various = [1, true, 'wayne', [false, 9]];
let age:number = 5;
let name: boolean = true;
let address: string = 'neverland';
let numbers: number [] = [1,2,3,4];
let counting: Array<number> = [1,2,3,4];
let tuple: [number, string] = [1, 'batman'];
let various: any[] = [1, true, 'wayne', [false, 9]];

Types

Variable type annotations

Interfaces

Code contract

It's a code contract

You were asked to build this:

But built this:

Which is like coding this:

instead of this:

let person = {
    fname: 'Bruce',
    lname: 'Wayne'
}
let person = {
    firstName: 'Bruce',
    lastName: 'Wayne'
}
interface Person {
    firstName: string;
    lastName: string;
    age?: number;
}
let person: Person {
    firstName: 'Yahiko'
}
let person: Person {
    firstName: 'Yahiko',
    lastName: 'Nagashi'
}

age has a ? and is optional

class Trainer implements Person {
    firstName: string;
    lastName: string;

    constructor(p: Person){
        this.firstName = p.firstName;
        this.lastName = p.lastName;
    }

    getUser(): Person {
        return {
            firstName: this.firstName,
            lastName: this.lastName
        }
    }
}

As a class interface

As a type

Generics

Code template

Code stencils or templates

export class List<T> {
    list: Array<T> = new Array<T>();
    add(item: T) {
        this.list.push(item);    
    }
}

let people = new List<string>();
people.add('Bruce');
people.add(211); //error
export class List<T> {
    list: Array<T> = new Array<T>();
    add(item: T) {
        this.list.push(item);    
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

let people = new List<Person>();
people.add({firstName: 'Bruce', lastName: 'banner'});
people.add(211); //error

Project Setup

Let's proceed if you can see the app running in your browser at http://localhost:9000

NodeJS

Browser

Browser

rxjs

core-js

zone.js

@angular/core

@angular/common

@angular/compiler

@angular/platform-browser

@angular/platform-browser-dynamic

Bootstrap and first Component

Let's move to the editor and start writing some Angular code

  • Remove all the code in app.component.ts
  • Rewrite component code
  • Remove all the code in app.module.ts
  • Rewrite the module code
  • Remove all the code in app.module.ts
  • Rewrite the module code

Templating Fundamentals

{{ }} - is the interpolation syntax

 

{{ title }}

{{ (1 + 2) / 3 }}

 

Evaluates the Javascript expression between {{ <expression here> }}

Interpolation and Expressions

Interpolation and Expressions

  • add a title property with type string
  • initialize the title property with "My App"
  • remove the title from the template
  • interpolate title property in template to display title

[] - is the property binding syntax

 

Any property of an HTML element can be bound to a property of the component

 

<h1 [innerHtml]="title"></h1>

Property binding

Bind the innerHtml property to the title property from the Component

Property binding

() - is the event binding syntax

 

Any event of an HTML element can be bound to a property of the component

 

<button (click)="onClick($event)">Click !</button>

Event binding

  • create an onClick function which alerts hello world
  • create a button in the template with the text Click!
  • attach the onClick function on click event of the button

Event binding

[()] - is the two-way binding syntax

 

Often used with the ngModel property from 

@angular/forms

 

<input type="text" [(ngModel)]="name"/>

Two-way binding

  • install @angular/forms
  • import FormsModule into module
  • create a name property on the component
  • create an input field on the template
  • two-way bind the name property on the input

Two-way binding

# - is the syntax to create a template ref

 

Creates a reference to the HTML element and makes it available inside the template

 

<input type="text" #someinput />

Template ref variables

Let's do an exercise

Angular Fundamentals

By Mohammad Umair Khan

Angular Fundamentals

Angular Fundamentals slide deck for the 10Pearls University Angular course.

  • 1,048