Paidiblog825102560.files.wordpress.com



Unit-44.1 Introduction to Express.jsExpress.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications. It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack. The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components; 1) MongoDB - The standard NoSQL database 2) Express.js - The default web applications framework 3) Angular.js - The JavaScript MVC framework used for web applications 4) Node.js - Framework used for scalable server-side and networking applications. The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests. 4.2 Installation of ExpressInstalling and using ExpressExpress gets installed via the Node Package manager. This can be done by executing the following line in the command line npm install express The above command requests the Node package manager to download the required express modules and install them accordingly. 4.2.1 Node Package Manager(npm)npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJSThere are two ways to install a package using npm: globally and locally.Globally ? This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code.npm install -g <package-name>Locally ? This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag.npm install <package-name>InstallingAssuming you’ve already installed Node.js, create a directory to hold your application, and make that your working directory.$ mkdir myapp$ cd myappUse the npm init command to create a package.json file for your application. $ npm initThis command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:entry point: (index.js)Enter app.js, or whatever you want the name of the main file to be. If you want it to be index.js, hit RETURN to accept the suggested default file name.Now install Express in the myapp directory and save it in the dependencies list. For example:$ npm install express --saveAbout package.json package.json - this file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project's dependencies. It can also contain other metadata such as a project description, the version of the project in a particular distribution, license information, even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project4.2 Creating the first Express application:Step 1: Create a directory myapp and install express in myapp directorynpm install express –saveThe install command will install express . You will now be able to see a node_modules folder get created in the root of your project. This is a crucial step, as you will be able to require any of the recently installed files in your own application files. The addition of —save will save the package to your dependencies list, located in the package.json, in your myapp directoryStep 2: Start your text editor of choice and create a file named app.js.?Write the following code:var express = require("express");var app = express();app.get('/',function(req,res){ res.send("Hello world")})app.listen(5000)The first line declares a variable which will contain the module called express, grabbing it from the node_modules folder. The express module returns a function. This function returns an object which can be used to configure Express application (app)The app.get() function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc.The app.send() function takes an object as input and it sends this to the requesting client. Here we are sending the string "Hello World!".The app.listen() function binds and listens for connections on the specified host and port. The listen method starts a server and listens on port 3000 for connections.It responds with “Hello World!” for get requests to the root URL (/)4.3 Application, Request and response Objects of Express.js(i) Express.js Application objectThe app object conventionally denotes the Express application. Create it by calling the top-level express() function exported by the Express module:var express = require('express');var app = express();The app object has methods forRouting HTTP requests; Configuring middleware; Rendering HTML views; Registering a template engine; app.METHOD(path, callback [, callback ...])Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so onapp.route(path)Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).var app = express();app.route('/events').all(function(req, res, next) { // runs for all HTTP verbs first // think of it as route specific middleware!}).get(function(req, res, next) { res.json(...);}).post(function(req, res, next) { // maybe add a new event...});Example: app.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') }) .put(function (req, res) { res.send('Update the book') })app.render(view, [locals], callback)Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.Think of app.render() as a utility function for generating rendered view strings. Internally res.render() uses app.render() to render views.app.render('email', function(err, html){ // ...});app.render('email', { name: 'Tobi' }, function(err, html){ // ...});(ii) Express.js Request ObjectExpress.js Request and Response objects are the parameters of the callback function which is used in Express applications.The express.js request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.Syntax:app.get('/',?function?(req,?res)?{?????//?--??})??Request Object PropertiesThe following table specifies some of the properties associated with request object.IndexPropertiesDescription1.req.appThis is used to hold a reference to the instance of the express application that is using the middleware.2.req.baseurlIt specifies the URL path on which a router instance was mounted.3.req.bodyIt contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser.4.req.cookiesWhen we use cookie-parser middleware, this property is an object that contains cookies sent by the request.5.req.hostnameIt contains the hostname from the "host" http header.6.req.ipIt specifies the remote IP address of the request.7.req.paramsAn object containing properties mapped to the named route ?parameters?. For example, if you have the route /user/:name, then the "name" property is available as req.params.name. This object defaults to {}.8.req.pathIt contains the path part of the request URL.9.req.protocolThe request protocol string, "http" or "https" when requested with TLS.10.req.queryAn object containing a property for each query string parameter in the route.11.req.routeThe currently-matched route, a string.Request Object MethodsFollowing is a list of some generally used request object methods:req.accepts (types)This method is used to check whether the specified content types are acceptable, based on the request's Accept HTTP header field.Examples:req.accepts('html');??//=>?html???req.accepts('text/html');??//?=>??text/html???req.get(field)This method returns the specified HTTP request header field.Examples:req.get('Content-Type');??//?=>?"text/plain"??req.get('content-type');??//?=>?"text/plain"??req.get('Something');??//?=>?undefined??req.param(name [, defaultValue])This method is used to fetch the value of param name when present.Examples://??name=cvrreq.param('name')??//?=>?"cvr"??//?POST?name=cvr??req.param('name')??//?=>?"cvr"??//?/user/cvr?for?/user/:name???req.param('name')??//?=>?"cvr"??(iii) Express.js Response ObjectThe Response object (res) specifies the HTTP response which is sent by an Express app when it gets an HTTP request.It sends response back to the client browser.It facilitates you to put new cookies value and that will write to the client browser .Let's see some properties of response object.IndexPropertiesDescription1.res.appIt holds a reference to the instance of the express application that is using the middleware.2.res.headersSentIt is a Boolean property that indicates if the app sent HTTP headers for the response.3.res.localsIt specifies an object that contains response local variables scoped to the requestMethodsMethodDescriptionres.download()Prompt a file to be downloaded.res.end()End the response process.res.json()Send a JSON response.res.jsonp()Send a JSON response with JSONP support.res.redirect()Redirect a request.res.render()Render a view template.res.send()Send a response of various types.res.sendFileSend a file as an octet stream.res.sendStatus()Set the response status code and send its string representation as the response body.4.4. Express.js GET and POST RequestGET and POST both are two common HTTP requests used for building REST API's. GET requests are used to send only limited amount of data because data is sent into header while POST requests are used to send large amount of data because data is sent in the body.Express.js facilitates you to handle GET and POST requests using the instance of express.Get method facilitates you to send only limited amount of data because data is sent in the header. It is not secure because data is visible in URL bar.Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.index.html<html>??<body>??<form?action=""?method="GET">??First?Name:?<input?type="text"?name="first_name">??<br>??Last?Name:?<input?type="text"?name="last_name">??<input?type="submit"?value="Submit">??</form>??</body>??</html>?Example.jsvar?express?=?require('express');??var?app?=?express();??app.use(express.static('public'));????app.get('/index.html',?function?(req,?res)?{??res.sendFile(?__dirname?+?"/"?+?"index.html"?);??})??app.get('/example',?function?(req,?res)?{??response?=?{??first_name:req.query.first_name,??last_name:req.query.last_name??};??console.log(response);??res.end(JSON.stringify(response));??})??var?server?=?app.listen(8000,?function?()?{?? ??var?host?=?server.address().address??var?port?=?server.address().port??console.log("Example?app?listening?at?",?host,?port)?? ??})Example2.jsvar?express?=?require('express');??var?app=express();??app.get('/get_example2',?function?(req,?res)?{??res.send('<p>Username:?'?+?req.query['first_name']+'</p><p>Lastname:?'+req.query['last_name']+'</p>');??})??var?server?=?app.listen(8000,?function?()?{??var?host?=?server.address().address??var?port?=?server.address().port??console.log("Example?app?listening?at?",?host,?port)??})?4.5 Routing in Express.JSWeb frameworks provide resources such as HTML pages, scripts, images, etc. at different routes.The function used to define different routes in an application isapp.method(route,handler)The method be applied to any one of the HTTP requests methods – get, post, put, delete. An alternate method (all) also exists, which executes independent of the request type.Path is the route at which the request will run.Handler is a callback function that executes when a matching request type is found on the relevant route.Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).Each route can have one or more handler functions, which are executed when the route is matched.We define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests. There is a special routing method, app.all(), used to load middleware functions at a path for all HTTP request methodsThese routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.Route definition takes the following structure:app.METHOD(PATH, HANDLER)Where:app is an instance of express.METHOD is an HTTP request method, in lowercase.PATH is a path on the server.HANDLER is the function executed when the route is matched.Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.This route path will match requests to the root route, /.app.get('/', function (req, res) { res.send('root')})This route path will match requests to /about.app.get('/about', function (req, res) { res.send('about')})This route path will match requests to /random.text.app.get('/random.text', function (req, res) { res.send('random.text')})Route paths based on string patterns.This route path will match acd and abcd.app.get('/ab?cd', function (req, res) { res.send('ab?cd')})This route path will match abcd, abbcd, abbbcd, and so on.app.get('/ab+cd', function (req, res) { res.send('ab+cd')})This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.app.get('/ab*cd', function (req, res) { res.send('ab*cd')})This route path will match /abe and /abcde.app.get('/ab(cd)?e', function (req, res) { res.send('ab(cd)?e')})Route paths based on regular expressions:This route path will match anything with an “a” in it.app.get(/a/, function (req, res) { res.send('/a/')})This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.app.get(/.*fly$/, function (req, res) { res.send('/.*fly$/')})Route ParametersRoute parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.Route path: /users/:userId/books/:bookIdRequest URL: : { "userId": "34", "bookId": "8989" }To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params)})Route handlersYou can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.A single callback function can handle a route. For example:app.get('/example/a', function (req, res) { res.send('Hello from A!')})More than one callback function can handle a route (make sure you specify the next object). For example:app.get('/example/b', function (req, res, next) { console.log('the response will be sent by the next function ...') next()}, function (req, res) { res.send('Hello from B!')})An array of callback functions can handle a route. For example:var cb0 = function (req, res, next) { console.log('CB0') next()}var cb1 = function (req, res, next) { console.log('CB1') next()}var cb2 = function (req, res) { res.send('Hello from C!')}app.get('/example/c', [cb0, cb1, cb2])A combination of independent functions and arrays of functions can handle a route. For example:var cb0 = function (req, res, next) { console.log('CB0') next()}var cb1 = function (req, res, next) { console.log('CB1') next()}app.get('/example/d', [cb0, cb1], function (req, res, next) { console.log('the response will be sent by the next function ...') next()}, function (req, res) { res.send('Hello from D!')})app.route()You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. Here is an example of chained route handlers that are defined by using app.route().app.route('/book') .get(function (req, res) { res.send('Get a random book') }) .post(function (req, res) { res.send('Add a book') }) .put(function (req, res) { res.send('Update the book') })4.1 Angular2 architecture:Angular is a platform and framework for building client applications in HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.The basic building blocks of an Angular application are NgModules, which provide a compilation context for components. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a root module that enables bootstrapping, and typically has many more feature ponents define views, which are sets of screen elements that Angular can choose among and modify according to your program logic and data. Components use services, which provide specific functionality not directly related to views. Service providers can be injected into components as dependencies, making your code modular, reusable, and efficient.Both components and services are simply classes, with decorators that mark their type and provide metadata that tells Angular how to use them.The metadata for a component class associates it with a template that defines a view. A template combines ordinary HTML with Angular directives and binding markup that allow Angular to modify the HTML before rendering it for display.The metadata for a service class provides the information Angular needs to make it available to components through dependency injection (DI).An app's components typically define many views, arranged hierarchically. Angular provides the Router service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.4.1.1 ModuleModules help organize an application into cohesive functionality blocks by wrapping components, pipes, directives, and services. Angular applications are modular.Module is the block of code which is designed to perform a single task. We can export the module in form of class. Angular 2 applications have one or more modules. Every Angular application must have at least one module. If Angular application contains only one module, it is referring as root module. Every Angular application has one root module and many more featured modules.Angular module is a class which is decorated with @NgModule. NgModule takes a single metadata object and its properties describe the module. Following are the important properties of NgModule.exports - It is the subset of declarations which would be used in the component template of other module.imports - imports other modulesproviders - It is a creator of services. They can be accessible in all the parts of the application.bootstrap - The root module has to set the bootstrap property. It is used to host all other views.declarations - It declare the view class that belong to current module. There are three type of view classes supported by Angular components, directives, and pipes.4.1.2. Components Components are the most basic building block of an UI and Angular applications. A component controls one or more sections on the screen (what we call views)A component is self contained and represents a reusable piece of UI that is usually constituted by three important things: A piece of html code that is known as the viewA class that encapsulates all available data and interactions to that view through an API of properties and methods architectured by Angular. Here’s where we define the application logic (what it does to support the view)And the aforementioned html element also known as selector.Using the Angular @Component decorator we provide additional metadata that determines how the component should be processed, instantiated and used at runtime.For example we set the html template related to the view, then, we set the html selector that we are going to use for that component, we set stylesheets for that component.The Component passes data to the view using a process called Data Binding. This is done by Binding the DOM Elements to component properties. Binding can be used to display property values to the user, change element styles, respond to an user event, etc.4.1.2.1 Lifecycle HooksA component has a lifecycle managed by Angular.Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.Angular offers lifecycle hooks that provide visibility into these key life moments and the ability to act when they occur.A directive has the same set of lifecycle ponent lifecycle hooks overviewDirective and component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the lifecycle hook interfaces in the Angular core library.Each interface has a single hook method whose name is the interface name prefixed with ng. For example, the OnInit interface has a hook method named ngOnInit() that Angular calls shortly after creating the component.No directive or component will implement all of the lifecycle hooks. Angular only calls a directive/component hook method if it is defined.Lifecycle sequenceAfter creating a component/directive by calling its constructor, Angular calls the lifecycle hook methods in the following sequence at specific moments:HookPurpose and TimingngOnChanges() Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.Called before ngOnInit() and whenever one or more data-bound input properties change.ngOnInit() Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.Called once, after the first ngOnChanges().ngDoCheck() Detect and act upon changes that Angular can't or won't detect on its own.Called during every change detection run, immediately after ngOnChanges() and ngOnInit().ngAfterContentInit() Respond after Angular projects external content into the component's view / the view that a directive is in.Called once after the first ngDoCheck().ngAfterContentChecked() Respond after Angular checks the content projected into the directive/component.Called after the ngAfterContentInit() and every subsequent ngDoCheck().ngAfterViewInit() Respond after Angular initializes the component's views and child views / the view that a directive is in.Called once after the first ngAfterContentChecked().ngAfterViewChecked() Respond after Angular checks the component's views and child views / the view that a directive is in.Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().ngOnDestroy() Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks.Called just before Angular destroys the directive/component.4.1.3. TemplatesTemplates are used to define a component view. A template looks like regular HTML, but it also has some differences. Angular 2 templating system gives us a syntax to express the dynamic part of our HTML.In Angular 2, a component needs to have a view. To define a view, you can define a template inline (using template) or in a separate file (using templateUrl).Template inline:import {Component} from 'angular2/core';@Component({ selector: 'app', template: '<h1>Welcome</h1>'})export class App {}Separate file:import {Component} from 'angular2/core';@Component({ selector: 'app', templateUrl: 'components/app/ponent.html'})export class App {}4.1.4 Directives :Angular templates are dynamic. When Angular renders them, it transforms the DOM according to the instructions given by directives. A directive is a class with a @Directive() decorator.There are 3 types of directives:ComponentsStructural DirectivesAttribute Directives(i) ComponentsYou cannot create an Angular application without one. A component directive requires a view along with its attached behaviour. This type of directive adds DOM elements. The naming convention for components is: ponent.ts.import {Component} from 'angular2/core'@Component({? selector: 'my-app',? template: `<h3>The Super Button</h3><button (click)="btnClick()">Click Me</button>`? })export class App {????? btnClick() {??????? alert('You clicked me!');??? }}(ii) Structural Directives : Structural directives alter layout by adding, removing, and replacing elements in the DOM. Examples of built-in structural directives that ship with Angular 2 are ngIf, ngFor and ngSwitch<li *ngFor="let movie of movies"></li>?<movie-detail *ngIf="selectedMovie"></movie-detail>(iii) Attribute DirectivesAttribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name.The ngModel directive, which implements two-way data binding, is an example of an attribute directive. ngModel modifies the behavior of an existing element (typically <input>) by setting its display value property and responding to change events.<input [(ngModel)]="movie.name">4.1.5 ServicesA service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well. The main purpose of Angular Services is sharing resources across components. Take Component classes, they should be lean, component's job is to enable the user experience (mediate between the view and the application logic) and nothing more. They don't fetch data from the server, validate user input, or log directly to the console. They delegate such tasks and everything nontrivial to services. A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. By defining such processing tasks in an injectable service class, you make those tasks available to any component. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.1Services are fundamental to any Angular application, and components are big consumers of services as they help them being lean. Following three steps are required to create an Angular 2 Service.Import the injectable member.Add the @Injectable Decorator.Export Service class.Ex:import?{?Injectable?}?from?'@angular/core';????@Injectable()??export?class?MyService?{??????GetText()?{??????????return?"Text?From?Service";??????}??}??There are four simple steps to use/import Service in the component.Import the Service to the component.Add it as a provider.Include it through Dependency Injection.Use the Service function.?ponent.tsimport?{?Component?}?from?'@angular/core';??import?{?MyService?}?from?'./app.service';????@Component({????selector:?'test-app',????templateUrl:?'./app/example.html',?????providers:?[MyService]??})????export?class?AppComponent?{???????name?=?"Jignesh";??????messageText?=?'';????????constructor(private?_myService:?MyService)?{????????}??????onClickMe()?{????????????this.messageText?=?this._myService.GetText();????????}??}??Example.html?<div>??????<h4>Event?Binding</h4>??????<br/>???????<button?(click)="onClickMe()">Click?me!</button>????????<br/><br/>????????<span>?{{messageText}}?</span>??</div>????4.1.6 Dependency InjectionDependency Injection is the heart of Angular applications. ependency Injection is a combination of two terms, those are “Dependency” and “Injections”. Dependency is an object or service that can be used in any another object and Injection is a process of passing the dependency to a dependent object. It creates a new instance of class along with its required dependencies.It allows us to inject dependencies in different components across our applications, without needing to know, how those dependencies are created, or what dependencies they need themselvesDependency Injection in Angular 2 consists of three aspects:Injector - The injector object that exposes APIs to us to create instances of dependencies.Provider - A provider is like a recipe that tells the injector how to create an instance of a dependency. A provider takes a token and maps that to a factory function that creates an object.Dependency - A dependency is the type of which an object should be created.Example:popcorn.service.tsimport { Injectable } from '@angular/core';@Injectable()export class PopcornService { constructor() { console.log("Popcorn has been injected!"); } cookPopcorn(qty) { console.log(qty, "bags of popcorn cooked!"); }}And here’s how you would inject our Popcorn service it in a component:Component: ponent.tsimport { Component } from '@angular/core';import { PopcornService } from './popcorn.service';@Component({ selector: 'app-root', templateUrl: './ponent.html', styleUrls: ['./ponent.css'], providers: [PopcornService]})export class AppComponent { constructor(private popcorn: PopcornService) {} cookIt(qty) { this.popcorn.cookPopcorn(qty); }}The cookIt() method in the template calls the cookPopcorn() method in the injected service. Let’s make use of our cookIt() method in our template:Template: ponent.html<input type="number" #qty placeholder="How many bags?"><button type="button" (click)="cookIt(qty.value)"> Cook it!</button>4.1.7 Data BindingData binding is the connection bridge between View and the business logic (View Model) of the application. Data binding in Angular is the automatic synchronization between Model and the View. When the Model changes, the Views are automatically updated and vice-versa. There are many ways to bind the data in Angular. Following are the types of data binding in Angular 2.InterpolationOne-way binding (unidirectional)Two-way binding Event binding(i) Interpolation: In interpolation, we need to supply property name in the View template, enclosed in double curly braces, e.g. {{name}}. It is used for one-way binding (Component class to View only).ponent.tsimport?{?Component?}?from?'@angular/core';??@Component({????selector:?'test-app',????templateUrl:?'./app/databinding.html'??})??export?class?AppComponent?{???????name?=?'CVR';??} ?databinding.html<h4>Data?binding?in?Angular?2?Application</h4>??<div>??????<h5>Interpolation?Example</h5>??????Hello?{{name}}?!??</div> ?(ii) Property binding (One-way binding)Angular 2.0 uses HTML DOM element property for one-way binding. The square brackets are used with property name for one-way data binding in Angular 2. For example, if we want one-way binding between Model property and template View for textbox, we need to use [value].ponent.tsimport?{?Component?}?from?'@angular/core';??@Component({????selector:?'test-app',????templateUrl:?'./app/databinding.html'??})??export?class?AppComponent?{???????name?=?'CVR';??????welcomeText?=?'Welcome?Jignesh!'??} ?databinding.html<div> ?????<h5>One?way?binding?Example</h5>??????Hello?<span?[innerText]?=?"name"?></span>!??????<br/><br/>??????<input?type?=?'text'??[value]="welcomeText"?/>??</div> ?(iii) Event BindingAngular 2.0 directly uses the valid HTML DOM element events. For example, ng-click is now replaced with (click). The round brackets (parentheses) are used with DOM event name for event binding in Angular 2. ponent.tsimport?{?Component?}?from?'@angular/core';??@Component({????selector:?'test-app',????templateUrl:?'./app/databinding.html'??})??export?class?AppComponent?{???????messageText?=?'';??????onClickMe()?{??????????this.messageText?=?"Hi?Reader!";??????}??} ?databinding.html<div>??????<h5>Event?binding?Example</h5>???????<button?(click)="onClickMe()">Click?me!</button>??????<br/><br/>??????<span>?{{messageText}}?</span>??</div> ?(iv) Two-way bindingThe ng-model directive is used for two-way data binding in Angular 1.x, but it is replaced with [(ngModel)] in Angular 2.0. The ngModel directive is part of a built-in Angular module called "FormsModule". So, we must import this module in to the template module before using the ngModel directive.app.module.tsimport?{?NgModule?}??????from?'@angular/core';??import?{?BrowserModule?}?from?'@angular/platform-browser';??import?{?FormsModule?}?from?'@angular/forms';???import?{?AppComponent?}??from?'./ponent';????@NgModule({????imports:??????[?BrowserModule,?FormsModule],????declarations:?[?AppComponent],????bootstrap:????[?AppComponent?]??})??export?class?AppModule?{???} ?databinding.html<div>??????<h5>Two?way?binding?Example</h5>??????Enter?you?Name:??<input?[(ngModel)]="enterName"??/>??????<br/><br/>??????<span>?WelCome?{{enterName}}?!?</span>??</div> ?4.1.8 RoutingAngular 2 gives you the possibility of dividing your application into several views that you can navigate between through the concept of routing. Routing enables you to route the user to different components based on the url that they type on the browser, or that you direct them to through a link.The way you configure routes in Angular 2 is through a router configuration file with:A Routes array that will contain a collection of routesAn export that provides the router configuration to the rest of the application.We’ll start by creating a new file app.routes.ts in the app folder and import the Routes interface from the @angular/router module:import { Routes } from '@angular/router'Each route in Routes array maps a path to a component . We tell Angular 2 that this is our default route by creating an additional configuration to map an empty path to the persons path.And create the following Routes array:// Route config let's you map routes to componentsconst routes: Routes = [ // map '/new' to the NewCompComponent { path: 'new', component: NewCompComponent, }, ];The next step is to make our routes available to the rest of the application. In order to achieve that, we import the RouterModule from the @angular/router module:import { Routes, RouterModule } from '@angular/router'And export our own defined routes as follows:export const appRouterModule = RouterModule.forRoot(routes)The whole app.routes.ts route configuration file should now look like this:import { Routes, RouterModule } from '@angular/router'import { NewCompComponent } from './new-comp/new-ponent';// Route config let's you map routes to componentsconst routes: Routes = [ // map '/persons' to the people list component { path: 'new', component: NewCompComponent, },]export const appRouterModule = RouterModule.forRoot(routes)Now we update our application to use the routes that we have defined in our configuration file. The way to do that is by including the routing in our application module app.module.ts:import { NgModule } from '@angular/core'import { FormsModule } from '@angular/forms'import { HttpModule } from '@angular/http'import { AppComponent } from './ponent'import { NewCompComponent } from './new-comp/new-ponent';import { appRouterModule } from './app.routes'@NgModule({ declarations: [AppComponent, NewCompComponent], imports: [BrowserModule, FormsModule, HttpModule, appRouterModule], providers: [], bootstrap: [AppComponent],})export class AppModule {}Router-outletThe <router-outlet></router-outlet> selector is a placeholder for the component to be displayed. We use the router-outlet directive, an Angular 2 Routing directive that displays the active route (like ng-view).Update the ponent.html to use the router-outlet directive like this:<h1>{{title}}</h1><router-outlet></router-outlet> ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download