Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Angular Starter

Angular Starter

Hardik Pithva

October 24, 2016
Tweet

More Decks by Hardik Pithva

Other Decks in Programming

Transcript

  1. Overview • Complete JavaScript-based open-source front-end web application framework by

    Google • Providing a framework for client-side MVC and MVVM architectures • Used by Wolfram Alpha, NBC, Walgreens, Intel, Sprint, ABC News, etc • Approximately 8,400 sites out of 1 million tested
  2. Angular • Announced at the ng-Europe conference Sept. 2014 and

    released on Sept. 2016 • Not a version upgrade, but a complete rewrite • Build client applications in HTML and either JavaScript or a language (like Dart or TypeScript) that compiles to JavaScript.
  3. Typescript • Free and open source programming language by Microsoft

    • Strict superset of JavaScript • Adds optional static typing, generics, lambdas and class-based object-oriented programming to the language class Greeter { constructor(public greeting: string) { } greet() { return "<h1>" + this.greeting + "</h1>"; } }; var greeter = new Greeter("Hello, world!"); document.body.innerHTML = greeter.greet();
  4. Typescript (cont’d) • Basic Types • Interfaces • Classes •

    Functions • Generics • Enums • Symbols • Iterators and Generators • Triple-Slash Directives • Decorators
  5. Basic Types • Boolean → let isDone: boolean = false;

    • Number → let x: number = 6; • String → let color: string = "blue"; • Array → let list: number[]=[1,2,3]; or let list: Array<number>=[1,2,3]; • Tuple → let x: [string, number]; • Enum → enum Color {Red = 1, Green, Blue}; • Any → let notSure: any = 4; • Void → function warnUser(): void {...} • Null and Undefined → let u: undefined = undefined; / let n: null = null; • Never
  6. Interfaces and Classes interface LabelledValue { label: string; width?: number;

    readonly x: number; } class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } let greeter = new Greeter("world");
  7. Enums • Allows to define a set of named numeric

    constants. • Defined using the enum keyword enum Direction { Up, Down, Left, Right } let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]
  8. Symbols • A primitive data type, just like number and

    string • Created by calling the Symbol constructor let sym2 = Symbol("key"); let sym3 = Symbol("key"); sym2 === sym3; // false, symbols are unique
  9. Iterators and Generators let list = [4, 5, 6]; for

    (let i in list) { console.log(i); // "0", "1", "2", } for (let i of list) { console.log(i); // "4", "5", "6" }
  10. Triple-Slash Directives • Single-line comments containing a single XML tag.

    • The contents of the comment are used as compiler directives. • Valid at the top of the containing file • Only be preceded by single / multi-line comments, including other triple-slash directives /// <reference path="..." /> • This serves as a declaration of dependency between files.
  11. Decorators • Special kind of declaration that can be attached

    to a class declaration, method, accessor, property, or parameter • Provides a way to add annotations and a meta-programming syntax for class declarations and member • Available as an experimental feature of TypeScript; to enable it, one must enable the experimentalDecorators compiler option either on the command line or in tsconfig.json
  12. “My favorite feature is that the type system mimics the

    actual JS spec as well as the common JS practices in the community very closely, and so it feels very natural to use.” Miško Hevery
  13. Architecture • Modules • Components • Templates • Metadata •

    Data binding • Directives • Services • Dependency injection
  14. Module • Apps are modular, modularity system called Angular modules

    / NgModules. • At least one module, the root module, conventionally named AppModule. • Root or feature module, is a class with an @NgModule decorator. • Important properties are: ◦ declarations, exports, imports, providers, bootstrap
  15. Angular libraries • Library name begins with the @angular prefix.

    ◦ @angular/core → import { Component } from '@angular/core'; ◦ @angular/compiler ◦ @angular/common ◦ @angular/http ◦ @angular/platform-browser ◦ @angular/platform-browser-dynamic ◦ @angular/router ◦ @angular/upgrade
  16. Component • Controls a patch of screen called a view

    • Define a component's application logic—what it does to support the view—inside a class • Class interacts with the view through an API of properties and methods • Lifecycle hooks ◦ constructor -> ngOnChanges -> ngOnInit -> ngDoCheck ▪ -> ngAfterContentInit -> ngAfterContentChecked ▪ -> ngAfterViewInit -> ngAfterViewChecked ◦ -> ngOnDestroy
  17. Templates • Define a component's view with its companion template

    • Form of HTML that tells Angular how to render the component <p><i>Movie list</i></p> <ul> <li *ngFor="let movie of movies" (click)="selectMovie(movie)"> {{movie.name}} </li> </ul> <movie-detail *ngIf="selectedMovie" [movie]="selectedMovie"></movie-detail> • *ngFor, {{movie.name}}, (click), [movie], and <movie-detail> follows Angular's template syntax
  18. Metadata • Tells Angular how to process a class •

    In TypeScript, attach metadata by using a decorator • @Component decorator, which identifies the class immediately below it as a component class. ◦ Takes a required configuration object such as moduleId, selector, templateUrl, providers • The template, metadata, and component together describe a view
  19. Data binding • A mechanism for coordinating parts of a

    template with parts of a component • Add binding markup to the template HTML to tell Angular how to connect both sides • There are four forms of data binding syntax as follow: ◦ Interpolation : {{value}} ◦ Property binding : [property] = ”value” ◦ Event binding : (event) = ”handler” ◦ Two way data binding : [(ngModel)] = ”property”
  20. Directives • Templates are dynamic, prepares DOM according to the

    instructions given by directives • A directive is a class with directive metadata. • Apply the @Directive decorator to attach metadata to the class • A component is a directive-with-a-template; ◦ a @Component decorator is actually a @Directive decorator extended with template-oriented features. • Two other kinds of directives exist: structural and attribute directives.
  21. Directives (cont’d) • Structural directives alter layout by adding, removing,

    and replacing elements in DOM. <li *ngFor="let movie of movies"></li> <movie-detail *ngIf="selectedMovie"></movie-detail> • Attribute directives alter the appearance / behavior of an existing element. ◦ The ngModel directive, which implements two-way data binding, is an example of an attribute directive. ◦ <input [(ngModel)]="movie.name">
  22. Services • Broad category encompassing any value, function that application

    needs. • Typically a class with a narrow, well-defined purpose • Nothing specifically Angular about services, no definition, base class • Components; big consumers of services • Apply @Injectable() decorator to the class • Emits metadata about service, metadata
  23. Dependency injection • Way to supply a new class instance

    with the fully-formed dependencies • Injector main mechanism: ◦ maintains a container of service instances previously created ◦ makes a service instance and adds to the container if it’s not there • Calls the component's constructor with services as arguments after resolving and returning all requested services constructor(movieService: MovieService) {}
  24. Template basics Angular 1 Local variables <tr ng-repeat="movie in vm.movies">

    <td>{{movie.title}}</td> </tr> Bindings/interpolation My favorite movie is: {{vm.favoriteMovie}} Filters <td>{{movie.title | uppercase}}</td> Angular 2 Input variables <tr *ngFor="let movie of movies"> <td>{{movie.title}}</td> </tr> Bindings/interpolation My favorite movie is: {{favoriteMovie}} Pipes <td>{{movie.title | uppercase}}</td>
  25. Template directives Angular 1 ng-app <body ng-app="movieHunter"> angular.module("movieHunter", ["ngRoute"]); Angular

    2 Bootstrapping import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
  26. Template directives (cont’d) Angular 1 ng-controller <div ng-controller="MovieListCtrl as vm">

    angular .module("movieHunter") .controller("MovieListCtrl", ["movieService", MovieListCtrl]); function MovieListCtrl(movieService) { } Angular 2 Component decorator <movie-list></movie-list> @Component({ moduleId: module.id, selector: 'movie-list', templateUrl: 'movie-list.component.html', styleUrls:['movie-list.component.css'], }) export class MovieListComponent { }
  27. Template directives (cont’d) Angular 1 ng-click <button ng-click="vm.toggleImage()"> ng-src <img

    ng-src="{{movie.imageurl}}"> ng-hide/ng-show ng-href ng-if ng-model ng-repeat ng-style ng-switch Angular 2 bind to the click event (click)="toggleImage()" src <img [src]="{{movie.imageurl}}"> bind to the hidden property bind to the href property *ngIf ngModel *ngFor ngStyle ngSwitch
  28. Filters/pipes Angular 1 Filters angular.module('movieHunter', []) .filter('exponentialStrength', function() { return

    function(number, exponent) { var exp = parseFloat(exponent); return Math.pow(value, isNaN(exp) ? 1 : exp); }; }); Angular 2 Pipes import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'exponentialStrength'}) export class ExponentialStrengthPipe implements PipeTransform { transform(value: number, exponent: string): number { let exp = parseFloat(exponent); return Math.pow(value, isNaN(exp) ? 1 : exp); } } • A class decorated with pipe metadata • Implements the PipeTransform interface's transform method that accepts an input
  29. File structure • app ◦ core ◦ components ◦ shared

    • [root-files] <project root> app core core.module.ts exception.service.ts|spec.ts movies movie movie.component.ts|html|css|spec.ts shared movie-button.ts|html|css|spec.ts movie.model.ts movie.service.ts|spec.ts movies.component.ts|html|css|spec.ts movies.module.ts movies-routing.module.ts shared shared.module.ts Init-caps.pipe.ts|spec.ts seasons season … shared ... app.component.ts|html|css|spec.ts app.module.ts app-routing.module.ts main.ts index.html
  30. Prerequisite • Install Node.js (> 4.x.x.) and npm (>3.x.x) •

    Code editor (IntelliJ / VS Code or WebStorm)
  31. Configuration files • package.json ◦ identifies npm package dependencies for

    the project. • tsconfig.json ◦ defines how the TypeScript compiler generates JavaScript from the project's files. • systemjs.config.js ◦ provides information to a module loader about where to find application modules, and registers all the necessary packages.
  32. Configuration files (cont’d) • app/app.module.ts ◦ entry point to the

    application • app/app.component.ts ◦ at least one component a.k.a. the root component while others are feature • app/main.ts ◦ initializes the platform that your application runs in, then uses the platform to bootstrap your AppModule. • index.html
  33. package.json "dependencies": { "@angular/common": "~2.1.1", "@angular/compiler": "~2.1.1", "@angular/core": "~2.1.1", "@angular/forms":

    "~2.1.1", "@angular/http": "~2.1.1", "@angular/platform-browser": "~2.1.1", "@angular/platform-browser-dynamic": "~2.1.1", "@angular/router": "~3.1.1", "@angular/upgrade": "~2.1.1", "angular-in-memory-web-api": "~0.1.13", "bootstrap": "^3.3.7", "core-js": "^2.4.1", "reflect-metadata": "^0.1.8", "rxjs": "5.0.0-beta.12", "systemjs": "0.19.39", "zone.js": "^0.6.25" } "devDependencies": { "@types/core-js": "^0.9.34", "@types/node": "^6.0.45", "concurrently": "^3.0.0", "lite-server": "^2.2.2", "typescript": "^2.0.3" }
  34. package.json (cont’d) dependencies • Features - Feature packages give the

    application framework and utility capabilities • Polyfills - Polyfills plug gaps in the browser's JavaScript implementation • Other - Other libraries that support the application such as bootstrap for HTML widgets and styling devDependencies • concurrently • lite-server • typescript - • @types/*
  35. package.json (cont’d) Feature Packages • @angular/core - Critical runtime parts

    of the framework needed by every application • @angular/common - Commonly needed services, pipes & directives provided by Angular team • @angular/compiler - Angular's Template Compiler. It understands templates and can convert them to code that makes the application run and render. • @angular/platform-browser - Everything DOM and browser related, especially the pieces that help render into DOM. • @angular/platform-browser-dynamic - Includes Providers and a bootstrap method for applications that compile templates on the client. • @angular/http - Angular's http client.
  36. package.json (cont’d) Feature Packages (cont’d) • @angular/router - Component router.

    • @angular/upgrade - Set of utilities for upgrading Angular 1 applications. • system.js - A dynamic module loader compatible with the ES2015 module specification. Other viable choices include the well-regarded webpack. Polyfill packages • core-js - Patches the global context (window) with essential features of ES2015 (ES6) • reflect-metadata - A dependency shared between Angular and the TypeScript compiler. ◦ Update a TypeScript package without upgrading Angular, which is why this is a dependency of the application and not a dependency of Angular.
  37. package.json (cont’d) Polyfill packages (cont’d) • rxjs - A polyfill

    for the Observables specification currently before the TC39 committee that determines standards for the JavaScript language. • zone.js - A polyfill for the Zone specification currently before the TC39 committee that determines standards for the JavaScript language. Other helper libraries • angular-in-memory-web-api - An Angular-supported library that simulates a remote server's web api without requiring an actual server or real http calls. • bootstrap - Popular HTML and CSS framework for designing responsive web apps.
  38. package.json (cont’d) devDependencies • concurrently - A utility to run

    multiple npm commands concurrently on OS/X / Windows / Linux • lite-server - A light-weight, static file server, by John Papa with • typescript - the TypeScript language server, including the tsc TypeScript compiler. • @types/* - TypeScript definition files
  39. tsconfig.json • Browsers can't execute TypeScript directly • Transpiled into

    JavaScript using the tsc compiler requires some configuration • When the noImplicitAny flag is false, and if the compiler cannot infer the variable type based on how it's used, the compiler silently defaults the type to any
  40. tsconfig.json (cont’d) { "compilerOptions": { "target": "es5", // es3 or

    es5 or es6 "module": "commonjs", // amd or system or umd "moduleResolution": "node", "sourceMap": true, // transpile .js along with the associated '.map' files "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false, "outDir":"dist" //redirect all of transpiled files to specify directory } }
  41. Thanks! Contact : Hardik Pithva L&T Infotech 9 Mind Space

    Airoli MH 400708 (+91) 976 208 6487 [email protected] www.lntinfotech.com