1 / 56

Day 2

Day 2. Understanding Module, Module Bundler, Module Loader Using WebPack Angular2 Project Setup from Scratch Understanding Angular2 Core Concepts Communication Between Components. What is Type Script? - Review. TypeScript = JavaScript + Types. Data Types in TypeScript - Review.

carltonl
Download Presentation

Day 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Day 2 Understanding Module, Module Bundler, Module Loader Using WebPack Angular2 Project Setup from Scratch Understanding Angular2 Core Concepts Communication Between Components

  2. What is Type Script? - Review • TypeScript = JavaScript + Types

  3. Data Types in TypeScript - Review • Primitive Types • string • number • boolean • Special Types • any, void • Array Types • [ ] • Array • Function Types • Function • Object Types • { }

  4. Modules • Starting with the ECMAScript 2015, JavaScript has a concept of modules. TypeScript uses this concept. • Modularity deals with the process of breaking up complex systems into small, self contained pieces that can be managed easily. • Modules allows you to organize your code. • Module contain a set of Classes, Interfaces, etc., based on common operation like String Manipulation Module or Math Module etc. • Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module.

  5. Using Modules • The relationships between modules are specified in terms of imports and exports at the file level. • export keyword: In order to avail an Interface or Class or a function to a different TypeScript module you need to expose it using the export keyword. • import keyword: In order to access Class or an Interface of different module we need import it. • Each file is a module OR a module is in a file

  6. Hands On Example • Create Different Modules in separate file • Create module1.ts to export • Point and • Point3D • Use Point and Point3D from oopdemo.ts file. • Importing Module Members in another TS module file import {Point} from "./module1" • import {Point, Point3D} from "./module1“ • Importing all members import * as flow from “./module1”

  7. Module System Styles • There are multiple standards for how to define dependencies and export values: • CommonJS, AMD, UMD, RequireJS • Modules should be executed on the client, so they must be transferred from the server to the browser. • There are two extremes when transferring modules: • 1 request per module • All modules in one request • Modules are imported using a module loader. • At runtime the module loader is responsible for locating and executing all dependencies of a module before executing it. • Well-known modules loaders used in JavaScript are the WebPack, SystemJS.

  8. Web Pack • Web pack takes care of loading modules and it also bundles all our code into a single file, so that browser can load it in a single http request. • Module bundling is the process of combining a group of modules along with their dependencies together into a single file (or a bunch of files). • Install webpack to the project npmiwebpack –S

  9. Hands On Demo – Web Pack • In js folder, create app.js, child1.js, child2.js, grandchild.js files with console log messages in each file. • Create webpackdemo.html • Using dependencies in app.js file, use require() function to refer dependencies. • The app.js is dependent on child1.js and child2.js, In app.js const c1 = require("./child1.js") const c2 = require("./child2.js") console.log("This is APP Message") • child2.js depends on grandchild.js, in child2.js file const gc = require("./grandchild.js"); console.log("This is Child 2 File Message")

  10. Hands On Demo • In web page, refer app.js <script src="scripts/app.js"></script> throws an error • Module Dependencies and Bundling • Bundle JS files node_modules\.bin\webpack js\app.js js\mybundle.js • Refer mybundle.js file in webpage and verify the output.

  11. WebPack with TypeScript • Webpack supports only JS code. • But, we are using TS, so we need an additional package for that. • Web pack uses loaders to load different files. • Install ts-loader package. npm i ts-loader –D

  12. Hands On - Webpack Configuration File • Create webpack.config.js file in project folder module.exports = { entry: "./ts/oopdemo.ts", output: { path: __dirname+”/dist", filename: "appbundle.js" }, module: { loaders: [{test:/\.ts$/, loader:'ts-loader' }] }, resolve: { extensions: ['.js', '.ts'] } } • Create and Run web pack as NPM Task Runner"webpk": "webpack --watch",

  13. Web Pack Configuration File • Webpack will read a file webpack.config.js . This file should export the configuration object. • Configuration Object properties • entry: The entry point for the bundle. The string is resolved to a module which is loaded upon startup. • output: tell Webpack how to write the compiled files to disk. • output.filename: determines name of the output file on disk. • output.path: determines the location on disk the files are written. • module.loaders: An array of automatically applied loaders. • test: used to match the file extension. A condition in RegExp • loader: A string of loader. The loader is resolved relative to the resource which they are applied to. • resolve.extensions: An array of extensions that should be used to resolve modules.

  14. Hands On Example • Comment app.js reference in home page. • Refer appbundle.js in home page • Verify the output.

  15. Working with Other JS Libraries • To use the libraries not written in TypeScript such as jQuery, AngularJS, KnockoutJS etc.., we need to declare the API that the library exposes. • We just need to have TypeScript definition file for the library available. • Typically, these are defined in .d.ts files. • Typings is a package typescript uses to understand how the external libraries are used. • Typings basically is going to tell typescript all about these packages here that way typescript can give code hinting tells methods whichever libraries we are going to use.

  16. Decorators • Decorators in typescript are used to describe more information about a class or method or property or a data member. • Decorator is a function that adds meta data to a • Class • Its members or • Its method arguments • Prefixed with an @

  17. Angular2 Application Development • Angular is an open-source JavaScript framework developed by Google has been designed with modern web standards. • Using Web Storm IDE • Create a new Empty Project day2project • Create Home Page i.e. index.html

  18. Angular2 Project Dependencies • These dependencies provide functionality for our Angular2 that make our apps better. • es6-shim: Adds es6 features to browsers that don't have them • zone.js: An execution context. Helps with change detection and showing errors. Provides stack traces. • reflect-metadata: Polyfill for decorator metadata. Used to apply decorators to our code. • rxjs: Libraries that help create asynchronous data streams. Gives us Observables. The Angular 2 http library uses these heavily. • WebPack: We can load different modules across different files in our browser • Typescript: Allows us to apply types, oop features in app development. • Ts-loader: Helps to transpile and bundle TS file with webpack.

  19. Hands On Example • Install Angular2 Project dependencies npm i es6-shim reflect-metadata zone.js rxjs webpack typescript ts-loader –S • We need to install the typings (Type Definitions) for es6-shim library. npm install @types/es6-shim -S • Let’s organize our TS files in our project src folder and transpiled files in dist folder. • Create src folder in project and • Create main.ts file in src folder

  20. TS Configuration File • Create Type Script Configuration File { "compilerOptions": { "module": "commonjs", "target": "es5", "noImplicitAny": false, "sourceMap": false, "noEmitOnError": true, "rootDir": "src", "outDir": "dist" } }

  21. WebPack Configuration File • Create webpack.config.js file module.exports = { entry: "./src/main.ts", output: { path: "./dist", filename: "app.bundle.js" }, module: { loaders: [{test:/\.ts$/, loader:'ts-loader' }] }, resolve: { extensions: ['.js', '.ts'] } }

  22. Hands On Example • Modify Home Page i.e. index.html <!DOCTYPE html> <html lang="en"> <head> <title>First Angular App Example</title> </head> <body> <app-root>Angular is Loading. Please Wait...</app-root> <script src="dist/app.bundle.js"></script> </body> </html>

  23. NPM Task Runner • Create package.json file • Install lite-server and concurrently as Dev Dependency and save in package.json file. • Define task runners for webpack and lite-server "scripts": { "webpk": "webpack --watch", "lite": "lite-server", "start": "concurrently \"npm run webpk\" \"npm run lite\" " }, • npm start • Run the application in browser and verify Console. • Kill the NPM start.

  24. Angular2 Framework API • Angular is an open-source JavaScript framework developed by Google has been designed with modern web standards. • Visit: angular.io • Angular2 is a framework for all types of apps • Web Apps • Mobile Apps (Hybrid) • Desktop Apps • Angular API is organized in the form of modules. • A module is a collection of related classes, interfaces, decorators, services etc..,

  25. Angular Modules • Angular2 Application requires following modules. • @angular/core • @angular/common • @angular/compiler • @angular/platform-browser • @angular/platform-browser-dynamic • In command prompt, install the above packages in our project npm install @angular/core @angular/common @angular/compiler @angular/platform-browser @angular/platform-browser-dynamic -S

  26. Structure of Angular2 Application • Angular2 application is a set of components. We design and build each component individually and then stack them nicely to create our application. • We design each component to work with the others ultimately provide user experience. Constructing an Angular2 Component • Import External Modules • Add Meta Data • Create the Class

  27. Creating a Component • As per convention, each component will have .component.ts file app.component.ts • Define a class AppComponent export class AppComponent { } • Decorate the class with built-in @Component decorator @Component({ }) export class AppComponent {}

  28. TS Config file Settings • emitDecoratorMetadata: Emit design-type metadata for decorated declarations in source • experimentalDecorators: Enables experimental support for ES decorators. {"compilerOptions": { "module": "commonjs", "target": "es5", "sourceMap": true, "rootDir": "src", "outDir": "dist", "noEmitOnError": true,"experimentalDecorators": true,"emitDecoratorMetadata": true}}

  29. Hands On Example - Component • Provide meta data with two parameters: • selector and • template. • The selector parameter defines the tag to be used for the instance of the component on the html page. • And template defines the html content that will be displayed for the component. @Component({ selector: “app-root",template: “ <h3>Welcome to Angular2 Application</h3>” })

  30. Using the Component • To use component in angular2 app, we need to do TWO things • Need to create a angular module • And then we need to bootstrap it • In main.ts file • The module is a way we can encapsulate all of the different components of our application into one central location. • Define NgModule Decorator • imports: Any other modules we need to use BrowserModule here. • declarations: this is going to be components that we are using in our app • bootstrap: We need to use core component we need to use

  31. Hands On Example • Create app.module.ts file in src folder, and import required libraries for Angular2 Application 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 {}

  32. Initializing Angular2 Application • Angular2 application startup or initialization process is called bootstrapping an application, which really means that we are going to use our application and started up in our browser. • To initialize our angular2 application, we need to use bootstrapModule(ModuleName); function. • The platformBrowserDynamic module contains the functionality to run our application in the browser and loading our templates dynamically. • It’s also use angular outside the browser, mobile apps / server apps that’s why we are using dynamic browser.

  33. Hands On Example • In main.ts file import "reflect-metadata“ import "zone.js" import {platformBrowserDynamic} from "@angular/platform-browser-dynamic“ import {AppModule} from "./app.module"; platformBrowserDynamic().bootstrapModule(AppModule) • Start the npm task

  34. Handling Iterable Error • Open the respective file and i.e. node_modules/@angular/core/src/change_detection/differs/iterable_differs.d.ts • add the following to the top of the file declare type Iterable<T> = any; • and it compiles now.

  35. Passing Data to Template • Create a data member in Component Class export class AppComponent { pageHeading:string = “Wells Fargo" } • Interpolation: Use double-curly braces of interpolation, {{ and }} to bind data into the text between HTML element tags and within attribute assignments. • Bind the data member to View (Template) using {{ }} template: "<h1>{{pageHeading}}</h1>“ • Angular replaces that name with the string value of the corresponding component data member.

  36. Hands On Example – External View • Splitting the application into smaller components is a good practice in Angular 2 • Create partials folder in your project • Create a new html file app.component.html <h1>{{pageHeading}}</h1> • Modify component meta data porperty to refer external html view.templateUrl: “partials/app.component.html“

  37. Hands On Exercise • Create counter folder in src • Create a WebComponentcounter in counter.component.tsfile. @Component({selector: "counter",template: ` <h3>This is Counter Component Content</h3> `})export class CounterComponent {}

  38. Hands On Exercise • Create counter.module.ts file in counter folder @NgModule({ declarations: [CounterComponent]})export class CounterModule { } • Use <counter> component in <app-root> component view. • Modify app.component.html <h1>First Angular2 Example</h1><hr><counter></counter>

  39. Working with Child Components • Angular2 allows nesting a component inside another component. • The outer component is RootComponent / Parent Component and inner component is a Child Component. • We will create another component (Child Component) and we will see how to nest the child component inside the parent component.

  40. Angular Modules • Angular Modules help organize the source code of an application. • An Angular Module is a class decorated with @NgModule decorator function. • Every Angular app has at least one module class, the root module. • We bootstrap that module to launch the application. • As the app grows, we refactor the root module into feature modules that represent collections of related functionality. 

  41. Working with Feature Module • Use CounterModule as dependency to AppModule imports: [BrowserModule, CounterModule], • The CounterComponent should avail to AppModule, export the CounterComponent from CounterModule. declarations: [CounterComponent], exports: [CounterComponent]

  42. Hands on Exercise – Working with Model • Defining a Model • Create a data member count in CounterComponent export class CounterComponent {count:number= 0;} • Display count value in template • Multi Line Template: Typescript uses BackTick to work with multi line strings. • Interpolation Value of Count is {{count}}

  43. Event Binding • Define a method incrementCounter() in CounterComponent incrementCounter():void {this.count++;} • Create a button in template to increase the counter. <button>Increase</button> • To bind a click event for button, use the parentheses syntax, (click) <button (click)="incrementCounter()">Increase </button>

  44. Property Binding • Bind the count to textbox <input type="number" value="{{count}}"> • The [] square bracket notation here signifies a property binding. • The value is a property on the DOM object • To think about property binding in a simpler way, take element.value for example. • Applying Property Binding <input type="number" [value]="count">

  45. Passing data into Angular2 Components • In AppComponent, Declare a data member myCount with value as 10 and display in template. export class AppComponent {myCount:number = 10;} • Initialize the myCount data for count property • We need to tell Angular what is coming into our component. • @Input decorator is used to recieve input details from parent component.

  46. Hands On Example • Decorate count property with Input decorator @Input()count:number = 0; • We have to tell Angular the name of the property binding <counter [count]=“myCount"></counter>

  47. Custom Property Names • We want property names to differ from the internal input names. <counter [count]=“myCount"></counter> • To <counter [init]=“myCount"></counter> • We’ve changed [count] to [init], so how does this now affect our internal input binding inside the CounterComponent? @Input('init')count:number= 0;

  48. Passing Data from Child Component • Changes applied for count property when a button clicked, it should apply myCount in parent. • If the nested component wants to send information back to its container, it can raise an event.  • The nested component exposes an event it can use to pass output to its container using the @Output decorator. • However, the property type must be an event. • An event is defined with an EventEmitter object. • The event property uses emit method to raise an event and pass our data as an argument.

  49. Hands On Example • Passing data from Child to Parent @Output()myEvent= new EventEmitter(); • Emitting the event incrementCounter() {this.count++;this.myEvent.emit(this.count);} • Listening the event <counter [init]=“myCount" (myEvent)="onMyEvent($event)"></counter> • In App Component class define a method onMyEvent(val:number){this.myCount = val; }

  50. Data Binding • Data-binding is an automatic synchronization of data between a View (HTML) and Model (data). • Angular Supports • One-way data binding: Model to View • Two-way Data Binding: Model to View and Vice-versa • Apply two way binding with HTML form elements. • Two-Way Data Binding • Using both property binding and event binding [(ngModel)] • <input [(ngModel)]=‘property name’> <input type="number" [(ngModel)]="count"> • Throws an Error

More Related