Angular 4i Angular 4 About the Tutorial Angular 4 is a JavaScript framework for building web applications and apps in JavaScript, html, and TypeScript, which is a superset of JavaScript. Angular provides built-in features for animation, http service, and materials which in turn has features such as auto- complete, navigation, toolbar, menus, etc. The code is written in TypeScript, which compiles to JavaScript and displays the same in the browser. Audience This tutorial is designed for software programmers who want to learn the basics of Angular 4 and its programming concepts in a simple and easy manner. This tutorial will give you enough understanding on the various functionalities of Angular 4 with suitable examples. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of HTML, CSS, JavaScript, TypeScript, and Document Object Model (DOM). Copyright & Disclaimer Copyright 2017 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at
[email protected] i Angular 4 Table of Contents About the Tutorial .............................................................................................................................................................i Audience..............................................................................................................................................................................i Prerequisites .......................................................................................................................................................................i Copyright & Disclaimer .....................................................................................................................................................i Table of Contents ............................................................................................................................................................. ii 1. Angular 4 – Overview ......................................................................................................................................................1 Why Angular4 and Not Angular3? .................................................................................................................................1 2. Angular 4 – Environment Setup ....................................................................................................................................3 3. Angular 4 – Project Setup ...............................................................................................................................................6 4. Angular 4 – Components ............................................................................................................................................. 26 5. Angular 4 – Module ...................................................................................................................................................... 35 6. Angular 4 – Data Binding ............................................................................................................................................. 38 7. Angular 4 – Event Binding ........................................................................................................................................... 45 8. Angular 4 – Templates ................................................................................................................................................. 51 9. Angular 4 – Dire ctives .................................................................................................................................................. 55 How to Create Custom Directives?............................................................................................................................. 55 10. Angular 4 – Pipes ........................................................................................................................................................... 59 How to Create a Custom Pipe? .................................................................................................................................... 64 11. Angular 4 – Routing ...................................................................................................................................................... 67 12. Angular 4 – Services...................................................................................................................................................... 72 13. Angular 4 – Http Service .............................................................................................................................................. 81 14. Angular 4 – Forms ......................................................................................................................................................... 88 Template Driven Form .................................................................................................................................................. 88 Model Driven Form........................................................................................................................................................ 91 Form Validation.............................................................................................................................................................. 94 15. Angular 4 – Anim ations................................................................................................................................................ 99 ii .. 114 18................................ Angular 4 – CLI ............................................. 115 iii ........... Angular 4 – Examples .................................................................................................................... Angular 4 – Materials .................................. Angular 4 16................................... 105 17................................................................................................................................................................................ 1.</span> <ng-template #condition1>Condition is invalid</ng-template> as keyword in for loop With the help of as keyword you can store the value as shown below: <div *ngFor="let i of months | slice:0:5 as total"> Months: {{i}} Total: {{total. Angular 4 – Overview Angular 4 There are three major releases of Angular. However. Let us now see the new features and the changes made in Angular 4. Let us see how it works using the ng-template. Why Angular4 and Not Angular3? The Angular team faced some versioning issues internally with their modules and due to the conflict they had to move on and release the next version of Angular – the Angular4. else condition1">Condition is valid. Angular1 was followed by Angular2. The structure of Angular is based on the components/services architecture. Angular 4 is almost the same as Angular 2. Animation Package Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. which came in with a lot of changes when compared to Angular1. AngularJS was based on the model view controller. The first version that was released is Angular1. It has a backward compatibility with Angular 2. which is also called AngularJS. It is still kept the same for its backward compatibility aspect. 1 .length}} </div> The variable total stores the output of the slice using the as keyword. Angular 4 released in March 2017 proves to be a major breakthrough and is the latest release from the Angular team after Angular2. Angular 4 supports the if else condition as well. <span *ngIf="isavailable. Projects developed in Angular 2 will work without any issues with Angular 4. In Angular2. it was available with @angular/core. Let us now see the new features added to Angular 4: ngIf Angular2 supported only the if condition. It uses the TypeScript version 2. This is one of the major changes in Angular 4. which is 2. Http Search Parameters Search parameters to the http get api is simplified. Angular 4 Template Angular 4 uses <ng-template> as the tag instead of <template>. <div> <h2>{{ 'Angular 4 titlecase' | titlecase }}</h2> </div> The above line of code generates the following output – Angular 4 Titlecase.2 Angular 4 is updated to a recent version of TypeScript. The reason Angular 4 changed <template> to <ng-template> is because of the name conflict of the <template> tag with the html <template> standard tag. the latest version which makes the final compilation small in size. Smaller and Faster Apps Angular 4 applications are smaller and faster when compared to Angular2. It will deprecate completely going ahead.2. 2 . which changes the first letter of each word into uppercase. TypeScript 2. the latter was used in Angular2. We do not need to call URLSearchParams for the same as was being done in Angular2. Pipe Title Case Angular 4 has added a new pipe title case.2. This helps improve the speed and gives better type checking in the project. install nodejs on your system.0 If it does not print anything. Nodejs To check if nodejs is installed on your system. Angular 4 – Environment Setup Angular 4 In this chapter. 2. type node –v in the terminal. C:\>node –v v6.org/en/download/ of nodejs and install the package based on your OS. we will discuss the Environment Setup required for Angular 4. To install Angular 4. go the homepage https://nodejs. The homepage of nodejs will look like the following: 3 . To install nodejs. we require the following: Nodejs Npm Angular CLI IDE for writing your code Nodejs has to be greater than 4 and npm has to be greater than 3. This will help you see the version of nodejs currently installed on your system.11. Once nodejs is installed. Type npm install –g @angular/cli. It should display the version of the npm. Angular 4 Based on your OS. 4 . type npm –v in the terminal.0 Angular 4 installations are very simple with the help of angular CLI. install the required package. C:\>npm –v 5.io/ of angular to get the reference of the command.angular. npm will also get installed along with it. Visit the homepage https://cli.3. to install angular cli on your system. To check if npm is installed or not. You can use any IDE of your choice. 5 .. Visual Studio Code. Atom. etc. WebStorm. The details of the project setup is explained in the next chapter.e. Angular 4 You will get the above installation in your terminal. once Angular CLI is installed. i. The npm package gets installed along with nodejs. Angular4 uses TypeScript 2. we first need to make sure we have nodejs and npm installed with the latest version. 6 .1 version whereas Angular 2 uses TypeScript version 1. Angular 4 works on the same structure as Angular2 but is faster when compared to Angular2. Go to the nodejs site https://nodejs.8. the Angular team came up with Angular CLI which eases the installation. To get started with the installation. Go to this site https://cli. Angular 4 – Project Setup Angular 4 AngularJS is based on the model view controller. whereas Angular 2 is based on the components structure.io to install Angular CLI. This brings a lot of difference in the performance.org/en/.angular. To install Angular 4. You need to run through a few commands to install Angular 4. 3. 0.0 is recommended for users. Once nodejs is installed. you can check the version of node in the command line using the command. npm will also get installed along with it. 7 .11. Users who already have nodejs greater than 4 can skip the above process. Once nodejs is installed.11. Angular 4 The latest version of Nodejs v6. as shown below: The command prompt shows v6. node –v. 10. Now that we have nodejs and npm installed. type command npm –v in the terminal. let us run the angular cli commands to install Angular 4. The version of npm is 3. It will display the version of npm as shown below.10. Angular 4 To check the version of npm. You will see the following commands on the webpage: npm install -g @angular/cli //command to install angular 4 ng new Angular 4-app // name of the project cd my-dream-app ng serve 8 . To start with. Enter the above command to install Angular 4. Angular 4 Let us start with the first command in the command line and see how it works. we will create an empty directory wherein. 9 . we will run the Angular CLI command. The installation process will start and will take a few minutes to complete. the following Command Prompt appears: We have created an empty folder ProjectA4 and installed the Angular CLI command. run the following command in the terminal: ng -v 10 . Angular 4 Once the above command to install is complete. We have also used -g to install Angular CLI globally. you can create your Angular 4 project in any directory or folder and you don’t have to install Angular CLI project wise. To check the installation. Let us now check whether Angular CLI is installed or not. as it is installed on your system globally and you can make use of it from any directory. Now. we will use the following command: ng new projectname We will name the project ng new Angular 4-app.0 and also the OS details.0. To create a project in Angular 4. which is at present 1. Let us now run the above command in the command line. The above details tell us that we have installed angular cli successfully and now we are ready to commence with our project.11.2. Angular 4 We get the @angular/cli version. The node version running is 6. 11 . We have now installed Angular 4. Let us now create our first project in Angular 4. Change the directory in the command line .e. 12 . go to https://code. Let us now switch to the project created.visualstudio. Atom. i.com/ and click Downloa d for Windows. We will use Visual Studio Code IDE for working with Angular 4. It installs all the required packages necessary for our project to run in Angular 4. Angular 4 The project Angular 4-app is created successfully. To download Visual Studio Code..cd Angular 4-app. etc. you can use any IDE. which is in the directory Angular 4-app. WebStorm. Let us now take the project we have created using angular-cli. Angular 4 Click Download for Windows for installing the IDE and run the setup to start using IDE. 13 . The Editor looks as follows: We have not started any project in it . Let us open the Angular 4-app and see how the folder structure looks like. 14 . Angular 4 We will consider the Angular 4-app project. let us compile our project with the following command: ng serve 15 . Angular 4 Now that we have the file structure for our project. The web server starts on port 4200. Type the url http://localhost:4200/ in the browser and see the output. Once the project is compiled. Angular 4 The ng serve command builds the application and starts the web server. you will receive the following output: 16 . Angular 4 17 . If you see we have used port 4200. you will be directed to the following screen: Let us now make some changes to display the following content: “Welcome to Angular 4 project” We have made changes in the files – app.0. You can change the port if you wish using the following command: ng serve --host 0.0.ts.0 –port 4205 18 .html and app.component.component. Let us complete the project setup. Angular 4 Once you run http://localhost:4200/ in the browser. We will discuss more about this in our subsequent chapters. which is the default port that angular–cli makes use of while compiling. The package.0".0. tslint.json . src – This folder is where we will work on the project using Angular 4.conf.This is the config file for the editor.editorconfig .This basically contains the compiler options required during compilation.0.json . "@angular/platform-browser-dynamic": "^4. version of cli.It basically holds the project name.js . At present. you will get the following modules added in it. .0". "@angular/forms": "^4.0.js . tsconfig. etc.conf.0. . karma. "@angular/router": "^4.gitignore file should be committed into the repository. "@angular/animations": "^4.0. Mainly e2e is used for integration testing and helps ensure the application works fine.The npm package installed is node_modules.A .json .0". The Angular 4 app folder has the following file structure: . "@angular/http": "^4. node_modules . In case you need to add more libraries. "@angular/platform-browser": "^4. You can open the folder and see the packages available.js file. package.0. Angular 4 The Angular 4 app folder has the following folder structure: e2e .json .0.0.This is the testing configuration required for the application.0".end to end test folder. 19 .0.conf.0". "@angular/common": "^4.This is used for unit testing via the protractor. if you open the file in the editor.0". All the informat ion required for the project is provided in karma. "@angular/compiler": "^4.json file tells which libraries will be installed into node_modules when you run npm install. "@angular/core": "^4.0". you can add those over here and run the npm install command.0".0". in order to share the ignore rules with any other users that clone the repository.angular-cli.gitignore . protractor.This is the config file with rules to be considered while compiling. This will have the modules imported as shown above.component'. BrowserModule is part of the imports which is imported from @angular/platform-brow ser. 20 .This has reference to the default component created.This will have reference to the services created. you will see that the code has reference to different libraries. The service will be disc ussed in a subsequent chapter. providers: []. They are imported and saved into variables such as declarations. bootstrap: [AppComponent] }) export class AppModule { } declarations . Angular-cli has used these default libraries for the import – angular/core.e.. imports: [ BrowserModule ]. We will learn about creating new components in a different section. providers . At present .In declarations. i. AppComponent. which internally has a different file structure. platform-browser. providers./app.module. imports. The Appcomponent is the default component that is created whenever a new project is initiated. app.ts .If you open the file. import { BrowserModule } from '@angular/platform-browser'. The names itself explain the usage of the libraries. Angular 4 The src folder is the main folder. app It contains the files described below. These files are installed by angular-cli by default. imports . the reference to the components is stored. and bootstrap. import { NgModule } from '@angular/core'. import { AppComponent } from '. which are imported. bootstrap . @NgModule({ declarations: [ AppComponent ]. divdetails{ background-color: #ccc.com/angular/angular - cli/wiki">CLI Documentation</a></h2> </li> 21 .base64. <!--The content below is only a placeholder and can be replaced. .io/tutorial">Tour of Heroes</a></h2> </li> <li> <h2><a target="_blank" href="https://github.You can write your css structure over here. Right now.html .PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgi Pz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx 1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIi BpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGlua z0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9 IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1 sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4 dC9jc3MiPg0KCS5zdDB7ZmlsbDojRE QwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZ T4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAg MzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE 4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLj IgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgM jE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44 LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUw xMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LT QwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo="> </div> <h2>Here are some links to help you start: </h2> <ul> <li> <h2><a target="_blank" href="https://angular. } app.The html code will be available in this file.component.css . we have added the background color to the div as shown below. --> <div class="divdetails"> <div style="text-align:center"> <h1> Welcome to {{title}}! </h1> <img width="300" src="data:image/svg+xml. Angular 4 app.component. environment.The class for the component is defined over here.component. @Component({ selector: 'app-root'.ts environment. The folder contains two files.component. styleUrls: ['./app.blogspot.These are automatically generated files which contain unit tests for source component./app. etc.ts file.ts . interacting with other components.component. } Assets You can save your images. The processing will include activities such as connecting to the database.prod.css'] }) export class AppComponent { title = 'app'.html'. 22 .spec. app.ts . routing. Environment This folder has the details for the production or the dev environment. app. services. templateUrl: '. js files in this folder.ts Both the files have details of whether the final file should be compiled in the production environment or the dev environment.ca/">Angular blog</a></h2> </li> </ul> </div> This is the default html code currently available with the project creation. You can do the processing of the html structure in the .component. The structure of the file is as follows: import { Component } from '@angular/core'. Angular 4 <li> <h2><a target="_blank" href="http://angularjs. Angular 4 The additional file structure of Angular 4 app folder includes the following: favicon.ts file and will display the details from app.ts main. It starts with import ing the basic module which we need./app/app.ts is the file from where we start our project development. angular/platform- browser-dynamic. main. app.component.googleapis.module and environment is imported by default during angular-cli installation and project setup.html file.css" rel="stylesheet"> <meta name="viewport" content="width=device-width. import { environment } from '. import { AppModule } from '.module'. initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon. This is the selector which is used in app./environments/environment'.com/css?family=Roboto|Roboto+Mono" rel="stylesheet"> <link href="styles.googleapis.component.ico"> </head> <body> <app-root></app-root> </body> </html> The body has <app-root></app-root>.bundle. import { enableProdMode } from '@angular/core'.c7c7b8bf22964ff954d3. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts. Right now if you see angular/core.html This is the file which is displayed in the browser. index. 23 .ico This is a file that is usually found in the root directory of a website. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>HTTP Search Param</title> <base href="/"> <link href="https://fonts. When AppModule is called.html. } platformBrowserDynamic(). the file that is called is index.. i. Hence.ts which further calls the AppComponent based on the boostrap as follows: bootstrap: [AppComponent] In app. AppModule when the following code executes: platformBrowserDynamic().production) { enableProdMode(). there is a selector: app-root which is used in the index. The platformBrowserDynamic(). the unit test cases for testing the project will be handled.ts which calls the parent module .ts Here.module.bootstrapModule(AppModule) has the parent module reference AppModule.ts.e.bootstrapModule(AppModule). styles. Angular 4 if (environment. when it executes in the browser. it calls app.html file.component. The following will be displayed in the browser: polyfill. This will display the contents present in app.css This is the style file required for the project. Index.html internally refers to main.ts This is mainly used for backward compatibility. 24 .bootstrapModule(AppModule). test.html.component. Angular 4 tsconfig.d. typings. The final file structure looks as follows: 25 . tsconfig. it has the config details that need to be used to run the application.json This helps maintain the details for testing.app.json This is used during compilation.ts It is used to manage the TypeScript definition.spec. bootstrap: [AppComponent] }) export class AppModule { } The declarations include the AppComponent variable. it has some libraries which are imported and also a declarative which is assigned the appcomponent as follows: import { BrowserModule } from '@angular/platform-browser'.component. providers: [].ts app. Angular 4 – Components Angular 4 Major part of the development with Angular 4 is done in the components. If you open up the app. This becomes the parent component.css app.ts app.ts file. which gets displayed on the browser. imports: [ BrowserModule ].ts The above files were created by default when we created new project using the angular- cli command.component.module. @NgModule({ declarations: [ AppComponent ].component.component'. import { NgModule } from '@angular/core'. The file structure has the app component and it consists of the following files: app. We have seen the file structure in one of our previous chapters.spec.html file of the component.module. import { AppComponent } from '. 4.html app.component. Components are basically classes that interact with the ./app. which we have already imported. 26 . However. import { NewCmpComponent } from '.spec. the app component which is created by default will always remain the parent and the next components created will form the child components.component. etc. new-cmp. we can define the module. new-cmp.component. import { AppComponent } from '.component'.ts update src\app\app.component'.component./new-cmp/new-cmp.here.component.spec. ng g component new-cmp When you run the above command in the command line.component. if we go and check the file structure. new-cmp. import { NgModule } from '@angular/core'. Let us now run the command to create the component . you will receive the following output: C:\projectA4\Angular 4-app>ng g component new-cmp installing component create src\app\new-cmp\new-cmp.component.html .this can be used for unit testing.css . angular-cli has a command to create your own component .component. Angular 4 Now.css file for the new component is created.html file is created. we will get the new-cmp new folder created under the src/app folder.css create src\app\new-cmp\new-cmp.component. properties.ts .ts Now./app.module.ts file as follows: import { BrowserModule } from '@angular/platform-browser'. Changes are added to the app.module.ts .ts create src\app\new-cmp\new-cmp. The following files are created in the new-cmp folder: new-cmp.html create src\app\new-cmp\new-cmp. // includes the new-cmp component we created 27 . OnInit } from '@angular/core'. providers: []./new-cmp.html'. The component word marked in bold needs to be the same.ts file is generated as follows: import { Component.component. bootstrap: [AppComponent] //for bootstrap the AppComponent the main app component is given. NewCmpComponent // here it is added in declarations and will behave as a child component ]. Angular 4 @NgModule({ declarations: [ AppComponent. @Component({ // this is a declarator which starts with @ sign.component.component. // reference to the html file created in the new component. // here angular/core is imported . styleUrls: ['. }) export class AppModule { } The new-cmp. imports: [ BrowserModule ]. }) export class NewCmpComponent implements OnInit { constructor() { } ngOnInit() { } } 28 . // templateUrl: '.css'] // reference to the style file. selector: 'app-new-cmp'./new-cmp. When we hit the url in the http://localhost:4200/ browser. Take a look at the tag in the body section. <app-root></app-root> This is the root tag created by the Angular by default.component. it creates a new class called NewCmpComponent.ts file. it first executes the index. the app component.ts file. which is created by default becomes the parent component. Angular 4 If you see the above new-cmp.ico"> </head> <body> <app-root></app-root> </body> </html> The above is the normal html file and we do not see anything that is printed in the browser. This tag has the reference in the main.module'.In. ngOnInit is called by default when the class is executed. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'./env ironments/environment'. Let us check how the flow works. Any component added later becomes the child component. 29 . import { enableProdMode } from '@angular/core'. Now. which implements OnInit./app/app. import { environment } from '. which has a constructor and a method called ngOnInit().ht ml file which is shown below: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angular 4App</title> <base href="/"> <meta name="viewport" content="width=device-width. import { AppModule } from '. initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon. Let us now see the app. import { NgModule } from '@angular/core'. Component. the variable to store the reference of the app. providers: []. } platformBrowserDynamic(). NewCmpComponent ].. Let us now see the app. and the same is given to the bootstrap Module.component'. AppModule is imported from the app of the main parent module.component'. Angular 4 if (environment. imports: [ BrowserModule ].e./new-cmp/new-cmp. 30 .production) { enableProdMode().ts and the same is given to the bootstrap.bootstrapModule(AppModule).module. import { NewCmpComponent } from '.ts file.component. @NgModule({ declarations: [ AppComponent. the AppComponent is the name given. i. import { AppComponent } from '.ts file: import { BrowserModule } from '@angular/platform-browser'. bootstrap: [AppComponent] }) export class AppModule { } Here. which makes the appmodule load./app. templateUrl: '. Now that we have created a new component called new-cmp.component.component.module. The class AppComponent has a variable called title. Angular 4 import { Component } from '@angular/core'.html file that we saw above./app. The selector here is nothing but the tag which is placed in the index. --> <div style="text-align:center"> <h1> Welcome to {{title}}.ts has a reference to the new component created. which is displayed in the browser./app. It gets replaced with the value. styleUrls: ['.html'. </h1> </div> It has just the html code and the variable title in curly brackets. 31 .css'] }) export class AppComponent { title = 'Angular 4 Project!'. This is called binding. @Component({ selector: 'app-root'. styleUrls: ['. The same gets included in the app.ts file.module./app. We will discuss the concept of binding in a subsequent chapter. which is present in the app.ts file. The @Component uses the templateUrl called app./app.component.component.component. when the command is run for creating a new component.html'.component. app. templateUrl and styleUrl are given. } Angular core is imported and referred as the Component and the same is used in the Declarator as - @Component({ selector: 'app-root'.css'] }) In the declarator reference to the selector. templateUrl: '.html which is as follows: <!--The content below is only a placeholder and can be replaced. the p tag. i.html called new-cmp. Angular 4 Let us now check the new files created in new-cmp./new-cmp. 32 .component.component. @Component({ selector: 'app-new-cmp'. The . we have the html code.css'] }) export class NewCmpComponent implements OnInit { constructor() { } ngOnInit() { } } Here.html is as follows: <p> new-cmp works! </p> As seen above. The reference of the component is used in the declarator. templateUrl: '. styleUrls: ['.e.component. The style file is empty as we do not need any styling at present. we do not see anything related to the new component getting displayed in the browser.component.. The declarator has the selector called app-new-cmp and the templateUrl and styleUrl. OnInit } from '@angular/core'./new-cmp. Let us now add something and the same can be seen in the browser later. new-cmp. we have to import the core too. But when we run the project.html'.ts import { Component. html file as follows: <!--The content below is only a placeholder and can be replaced. templateUrl: '. </h1> </div> <app-new-cmp></app-new-cmp> When the <app-new-cmp></app-new-cmp> tag is added. styleUrls: ['.component. we have added one variable called new component and the value is “Entered in new component created”.html file and the new-cmp. app-new-cmp needs to be added in the app.component./new-cmp.html file of the new component created will get displayed on the browser along with the parent component data.component . new-cmp.--> <div style="text-align:center"> <h1> Welcome to {{title}}./new-cmp.. The above variable is bound in the .new-cmp.component.e. constructor() {} ngOnInit() { } } In the class. Angular 4 The selector.html file as follows: 33 . Let us see the new component .ts import { Component.ts file. i. @Component({ selector: 'app-new-cmp'. all that is present in the .component.html'.component.css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created". OnInit } from '@angular/core'. Angular 4 <p> {{newcomponent}} </p> <p> new-cmp works! </p> Now since we have included the <app-new-cmp></app-new-cmp> selector in the app.html) gets displayed on the browser as follows: Similarly.html which is the .html file as per our requirements.component. component .component. 34 .html file (new-cmp.html of the parent c omponent. the content present in the new component . we can create components and link the same using the selector in the app. In case you are developing a website.ts file by default and it looks as follows: import { BrowserModule } from '@angular/platform-browser'. providers: []. left. the header. footer. 5.module. To define module. 35 .component'. Angular 4 – Module Angular 4 Module in Angular refers to a place where you can group the components. pipes./app. directives. import { NgModule } from '@angular/core'. the ngmodule is created in the app. @NgModule({ declarations: [ AppComponent ]. import { AppComponent } from '. center and the right section become part of a module. and services. we can use the NgModule. imports: [ BrowserModule ]. When you create a new project using the Angular –cli command. which are related to the application. bootstrap: [AppComponent] }) export class AppModule { } The NgModule needs to be imported as follows: import { NgModule } from '@angular/core'. In case your application needs forms . If any new component gets created. Declaration It is an array of components created. NewCmpComponent ] Import It is an array of modules required to be used in the application. bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations. It can also be used by the components in the Declaration array. import s. providers: []. providers and bootstrap. imports: [ BrowserModule ]. The import in the @NgModule will be like the following: imports: [ BrowserModule. it will be imported first and the reference will be included in declarations as shown below: declarations: [ AppComponent. right now in the @NgModule we see the Browser Module imported. FormsModule ] 36 . Angular 4 The structure for the ngmodule is as shown below: @NgModule({ declarations: [ AppComponent ]. you can include the module as follows: import { FormsModule } from @angular/forms. For example. Angular 4 Providers This will include the services created. Bootstrap This includes the main app component for starting the execution. 37 . 6. Angular 4 – Data Binding Angular 4 Data Binding is available right from AngularJS, Angular 2 and is now available in Angular 4 as well. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser. The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the app.component.ts file and in app.component.html, the value is displayed. Let us now create a dropdown of months in the browser. To do that , we have created an array of months in app.component.ts as follows: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; // declared array of months. months = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; } The month’s array that is shown above is to be displayed in a dropdown in the browser. For this, we will use the following line of code: <!--The content below is only a placeholder and can be replaced. --> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : 38 Angular 4 <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to iterate over the months’ array, which in turn will create the option tag with the value present in the months. The syntax for in Angular is *ngFor = “let I of months” and to get the value of months we are displaying it in {{i}}. The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the same will be replaced using the curly brackets. Let us see the output of the above month’s array in the browser. The variable that is set in the app.component.ts can be bound with the app.component.html using the curly brackets; for example, {{}}. Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the value as true. Using the if statement, we can hide/show the content to be displayed. Example import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component. css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. 39 Angular 4 months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; //variable is set to true } <!--The content below is only a placeholder and can be replaced. --> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable">Condition is valid.</span> //over here based on if condition the text condition is valid is displayed. If the value of isavailable is set to false it will not display the text. </div> Output 40 templateUrl: '. } In this case./app. we have made the isavailable variable as false. styleUrls: ['. we will have to create the ng-template as follows: <ng-template #condition1>Condition is invalid</ng -template> 41 . Angular 4 Let us try the above example using the IF THEN ELSE condition. "September". "November". @Component({ selector: 'app-root'. isavailable = false. "October". months = ["January"./app. "March". "July". "May". To print the else condition. //array of months. "August". Example import { Component } from '@angular/core'. "April". "December"].css'] }) export class AppComponent { title = 'Angular 4 Project!'. "February".component.html'.component. "June". else condition1">Condition is valid. The same is assigned as an id to the ng-template.</span> <ng-template #condition1>Condition is invalid</ng-template> </div> If is used with the else condition and the variable used is condition1. --> <div style="text-align:center"> <h1> Welcome to {{title}}. The following screenshot shows the display in the browser. 42 . Angular 4 The full code looks like this: <!--The content below is only a placeholder and can be replaced. and when the available variable is set to false the text Condition is invalid is displayed. </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable. isavailable = true. "June".component. "December"]. import { Component } from '@angular/core'./app./app. "March". "May". templateUrl: '. "October". //array of months. we will make the variable isavailable as true. "July". months = ["January". "August".html'.css'] }) export class AppComponent { title = 'Angular 4 Project!'. } Now. Angular 4 Let us now use the if then else condition. styleUrls: ['. "April".component. "November". the condition is written in the following way: <!--The content below is only a placeholder and can be replaced. --> <div style="text-align:center"> <h1> Welcome to {{title}}. @Component({ selector: 'app-root'. "February". </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> 43 . In the html. "September". two templates are created with id #condition1 and #condition2. else condition2. The display in the browser is as follows: 44 . Now. Angular 4 <span *ngIf="isavailable. then condition1.</span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> If the variable is true. then condition1 else condition2">Condition is valid. html file.component. Angular 4 – Event Binding Angular 4 In this chapter. or a mouseover. When a user interacts with an application in the form of a keyboard movement. a mouse click. we will discuss how Event Binding works in Angular 4. we have defined a button and added a function to it using the click event. This is where event binding comes into picture.component. Let us consider an example to understand this better. app. 45 . it generates an event. 7. These events need to be handled to perform some kind of action. then condition1 else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid</ng -template> <ng-template #condition2>Condition is invalid</ng-template> </div> <button (click)="myClickFunction($event)">Click Me</button> In the app.html <!--The content below is only a placeholder and can be replaced. </h1> </div> <div> Months : <select> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable. --> <div style="text-align:center"> <h1> Welcome to {{title}}. styleUrls: ['. "March". console./app. Angular 4 Following is the syntax to define a button and add a function to it. "August". the control will come to the function myClickFunction and a dialog box will appear. "October".css'] }) export class AppComponent { title = 'Angular 4 Project!'.html'./app. months = ["January". "June".log which will display the event details in browser on click of the button. } } Upon clicking the button. alert("Button is clicked"). @Component({ selector: 'app-root'. "December"]. templateUrl: '. isavailable = true. myClickFunction(event) { //just added console.component.log(event). "May".component.ts file: app.component. //array of months. "September". "November". import { Component } from '@angular/core'.ts. "Feburary". "April". which displays the Button is clicked as shown in the following screenshot: 46 . "July". (click)="myClickFunction($event)" The function is defined in the . then condition1 else condition2">Condition is valid. --> <div style="text-align:center"> <h1> Welcome to {{title}}. Angular 4 Let us now add the change event to the dropdown. </h1> </div> <div> Months : <select (change)="changemonths($event)"> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable. The following line of code will help you add the change event to the dropdown: <!--The content below is only a placeholder and can be replaced.</span> <ng-template #condition1>Condition is valid</ng -template> <ng-template #condition2>Condition is invalid</ng-template> </div> <button (click)="myClickFunction($event)">Click Me</button> 47 . component. "April".css'] }) export class AppComponent { title = 'Angular 4 Project!'. //array of months. "September". "June".component. myClickFunction(event) { alert("Button is clicked")./app. isavailable = true. "March".component./app. "May". styleUrls: ['. "July". months = ["January". console.log(event). @Component({ selector: 'app-root'. } } The console message “Changed month from the Dropdown” is displayed in the console along with the event. Angular 4 The function is declared in the app. "December"]. templateUrl: '. "November". "Feburary".log(event). console. 48 .html'. } changemonths(event) { console.ts file: import { Component } from '@angular/core'.log("Changed month from the Dropdown" ). "August". "October". } } 49 . "November".log which will display the event details in browser on click of the button. "October".html'. "December"]. "August"./app. templateUrl: '. "July". } changemonths(event) { alert("Changed month from the Dropdown"). styleUrls: ['. console. alert("Button is clicked"). "May".log(event). //array of months. "March".ts when the value from the dropdown is changed as shown below: import { Component } from '@angular/core'. "April". Angular 4 Let us add an alert message in app. isavailable = true. @Component({ selector: 'app-root'./app. "June". "September".component. myClickFunction(event) { //just added console.component. months = ["January".css'] }) export class AppComponent { title = 'Angular 4 Project!'.component. "February". a dialog box will appear and the following message will be displayed .“Changed month from the Dropdown”. Angular 4 When the value in dropdown is changed. 50 . html <!--The content below is only a placeholder and can be replaced. </h1> </div> <div> Months : <select (change)="changemonths($event)" name="month"> <option *ngFor="let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf="isavailable.component. 51 . The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. This is one of the major changes in Angular 4. app. It will deprecate completely going ahead. we have added the if statement with the else condition and will call template condition1.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click)="myClickFunction($event)">Click Me</button> For the Span tag.then condition1 else condition2">Condition is valid. Angular 4 – Templates Angular 4 Angular 4 uses the <ng-template> as the tag instead of <template> which is used in Angular2. else condition2. --> <div style="text-align:center"> <h1> Welcome to {{title}}. 8. Let us now use the template along with the if else condition and see the output. "May". otherwise condition2. "October". templateUrl: '.css'] }) export class AppComponent { title = 'Angular 4 Project!'.html'. then the condition1 template is called./app. styleUrls: ['. isavailable = false.component. "November". } } 52 . @Component({ selector: 'app-root'./app. //array of months.ts import { Component } from '@angular/core'. "July". "September". } changemonths(event) { alert("Changed month from the Dropdown").component. "March". "December"]. "April". myClickFunction(event) { this. "February". console.isavailable = false. Angular 4 The templates are to be called as follows: <ng-template #condition1>Condition is valid from template</ng -template> <ng-template #condition2>Condition is invalid from template</ng-template> If the condition is true. "June".component. app.log(event). months = ["January". "August". the respective template will be called. It has the Condition is invalid from template in the dom. If you inspect the browser. --> <div style="text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change)="changemonths($event)" name="month"> <option *ngFor="let i of months">{{i}}</option> </select> 53 . The following example will help you understand the same. you will see that you never get the span tag in the dom. <!--The content below is only a placeholder and can be replaced. Angular 4 The output in the browser is as follows: The variable isavailable is false so the condition2 template is printed. The following line of code in html will help us get the span tag in the dom. If you click the button. you will see that the dom does not have the span tag. If you inspect the browser. we have made the isavailable variable as true. For example. else condition2">Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click)="myClickFunction($event)">Click Me</button> If we remove the then condition.component. Angular 4 </div> <br/> <div> <span *ngIf="isavailable. in app.ts. we get the “Condition is valid” message in the browser and the span tag is also available in the dom. 54 . How to Create Custom Directives? In this section.module.directive. instantiated and used at runtime. Let us see how to create the custom directive. We will create the directive using the command line. For example. which is declared as @directive. Custom directives are created by us and are not standard. Structural directives have a * sign before the directive.ts 55 . Angular 4 – Directives Angular 4 Directives in Angular is a js class. Attribute Directives Attribute directives deal with changing the look and behavior of the dom element. The directives are listed below: Component Directives These form the main class having details of how the component should be processed.spec. You can create your own directives as shown below.directive. We have 3 directives in Angular. *ngIf and *ngFor.g ng g directive changeText This is how it appears in the command line: C:\projectA4\Angular 4-app>ng g directive changeText installing directive create src\app\change-text.ts update src\app\app.ts create src\app\change-text. Structural Directives A structure directive basically deals with manipulating the dom elements. The command to create the directive using the command line is: ng g directive nameofthedirective e. 9. we will discuss about Custom Directives to be used in components. module. NewCmpComponent. import { AppComponent } from '.directive. bootstrap: [AppComponent] }) export class AppModule { } The ChangeTextDirective class is included in the declarations in the above file.module.ts get created and the app.component'. change-text./change-text. import { ChangeTextDirective } from '.component'. i.directive'. ChangeTextDirective ]. The class is also imported from the file given below.ts import { BrowserModule } from '@angular/platform-browser'. imports: [ BrowserModule ]. import { NewCmpComponent } from '. @NgModule({ declarations: [ AppComponent.ts file is updated. Angular 4 The above files.ts and change-text./new-cmp/new-cmp.. providers: [].spec./app.directive. import { NgModule } from '@angular/core'. app.e. 56 . directive import { Directive } from '@angular/core'. let us add the directive as follows: <div style="text-align:center"> <span changeText >Welcome to {{title}}. Element.</span> </div> We will write the changes in change-text.ts file as follows: change-text.directive.nativeElement. @Directive({ selector: '[changeText]' }) export class ChangeTextDirective { constructor(Element: ElementRef) { console. Whatever we define in the selector. where we assign the custom directive.html view.innerText="Text is changed by changeText Directive. ElementRef} from '@angular/core'. ". Angular 4 change-text. In the app. } } 57 .component.ts import { Directive.directive. the same has to match in the view. @Directive({ selector: '[changeText]' }) export class ChangeTextDirective { constructor() { } } The above file has a directive and it also has a selector property.log(Element). The text of the element is also changed as shown above. there is a class called ChangeTextDirective and a constructor. We have added the console. which is mandatory. Angular 4 In the above file. 58 . which takes the element of type ElementRef.log element. The element has all the details to which the Change Text directive is applied. The output of the same can be seen in the browser console. the browser will show the following. Now. arrays./app.css'] }) export class AppComponent { title = 'Angular 4 Project!'. <b>{{title | uppercase}}</b><br/> <b>{{title | lowercase}}</b> 59 .component. Let us consider a few examples using pipes.ts file. } The following line of code goes into the app. Here.ts import { Component } from '@angular/core'.component. we want to display the text given to uppercase. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4. This can be done using pipes as follows: In the app. templateUrl: '. The | character is used to transform data. @Component({ selector: 'app-root'. we have defined the title variable: app. styleUrls: ['.component. and date as input separated with | to be converted in the format as required and display the same in the browser. Following is the syntax for the same: {{ Welcome to Angular 4 | lowercase}} It takes integers. strings.html file.component./app.html'. we will discuss what are Pipes in Angular 4. 10. Angular 4 – Pipes Angular 4 In this chapter.component. component. @Component({ selector: 'app-root'. The pipes are listed below: Lowerc asepipe Uppercasepipe Datepipe Currencypipe Jsonpipe Percentpipe Decimalpipe Slicepipe We have already seen the lowercase and uppercase pipes. styleUrls: ['.css'] }) 60 .html'.ts file: import { Component } from '@angular/core'. Angular 4 The browser appears as shown in the following screenshot : Angular 4 provides some built-in pipes.component./app. templateUrl: './app. Let us now see how the other pipes work. The following line of code will help us define the required variables in app.component. a2:'Karnataka'}}. "July". "Mar". jsonval = {name:'Rox'. "Feb". "April". age:'25'.border:solid 1px black. address:{a1:'Mumbai'. <!--The content below is only a placeholder and can be replaced.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.78787814 | number: '3.23 | currency:"USD"}}</b><br/> <b>{{6589. "Aug".border:solid 1px black. months = ["Jan"."> <div style="width:40%. "Jun". "Oct". </div> <div style="width:40%.html file. } We will use the pipes in the app. "Nov".component."> <h1>Json Pipe</h1> 61 . 4 -4 are for integers to be displayed. <h1>Date pipe</h1> <b>{{todaydate | date:'d/M/y'}}</b><br/> <b>{{todaydate | date:'shortTime'}}</b> <h1>Decimal Pipe</h1> <b>{{ 454.float:left. "Sept". todaydate = new Date(). "Dec"].float:left. Angular 4 export class AppComponent { title = 'Angular 4 Project!'. --> <div style="width:100%.4-4' }}</b> // 3 is for main integer."> <h1>Uppercase Pipe</h1> <b>{{title | uppercase}}</b><br/> <h1>Lowercase Pipe</h1> <b>{{title | lowercase}}</b> <h1>Currency Pipe</h1> <b>{{6589. "May". 54565 | percent}}</b> <h1>Slice Pipe</h1> <b>{{months | slice:2:6}}</b> // here 2 and 6 refers to the start and the end index </div> </div> 62 . Angular 4 <b>{{ jsonval | json }}</b> <h1>Percent Pipe</h1> <b>{{00. Angular 4 The following screenshot s show the output for each pipe: 63 . ts import {Pipe. We have given the same name to the file and it looks as follows: app.sqrt. Angular 4 How to Create a Custom Pipe? To create a custom pipe. we want to create the sqrt custom pipe. @Pipe ({ name : 'sqrt' }) 64 . PipeTransform} from '@angular/core'. we have created a new ts file. Here. ts. we need to add the same in app./app. we have to create the class and the class name is SqrtPipe. we have to give the name to our pipe./new-cmp/new-cmp.component'.directive'. Since. we are creating the sqrt pipe. @NgModule({ declarations: [ SqrtPipe. we have to import Pipe and Pipe Transform from Angular/core.component'. import { NgModule } from '@angular/co re'.module.html file. import { SqrtPipe } from '. In the @Pipe directive. Angular 4 export class SqrtPipe implements PipeTransform { transform(val : number) : number { return Math. imports: [ BrowserModule ]. NewCmpComponent. The transform method defined in the class will take argument as the number and will return the number after taking the square root. ChangeTextDirective ]. Since we have created a new file. As we proceed further.sqrt'. providers: []. import { ChangeTextDirective } from '. which will be used in our . This class will implement the PipeTransform.sqrt(val)./app. import { NewCmpComponent } from '. } } To create a custom pipe. import { AppComponent } from '. bootstrap: [AppComponent] }) export class AppModule { } 65 . AppComponent. we will name it sqrt./change-text. This is done as follows: import { BrowserModule } from '@angular/platform-browser'. module. Angular 4 We have created the app.ts class.html file. We have to import the same in app.sqrt. Let us now see the call made to the sqrt pipe in the app.component.ts and specify the path of the file. <h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b><br/> <b>Square root of 729 is: {{729 | sqrt}}</b> The output looks as follows: 66 . It also has to be included in the declarations as shown above. @NgModule({ declarations: [ SqrtPipe.sqrt'. You have seen many sites with links that direct you to a new page. Here the pages that we are referring to will be in the form of components. import { RouterModule} from '@angular/router'. providers: [].module.component'. This can be achieved using routing./new-cmp/new-cmp.ts. import { NewCmpComponent } from '. import { SqrtPipe } from '. NewCmpComponent.forRoot([ { path: 'new-cmp'./app. import { ChangeTextDirective } from '. we have to now include the router module as shown below: import { BrowserModule } from '@angular/platform-browser'./change-text. We have already seen how to create a component. import { NgModule } from '@angular/core'. In the main parent component app.directive'. imports: [ BrowserModule. Angular 4 – Routing Angular 4 Routing basically means navigating between pages.component'. RouterModule. 11./app. component: NewCmpComponent } ]) ]. bootstrap: [AppComponent] }) 67 . Let us now create a component and see how to use routing with it. AppComponent. ChangeTextDirective ]. import { AppComponent } from '. css'] }) export class NewCmpComponent implements OnInit { newcomponent = "Entered in new component created". the RouterModule is imported from angular/router.component. the component created. Let us now see the component created file: New-cmp.forRoot([ { path: 'new-cmp'./new-cmp. The module is included in the imports as shown below: RouterModule. component: NewCmpComponent } ]) ] RouterModule refers to the forRoot which takes an input as an array. i. @Component({ selector: 'app-new-cmp'. OnInit } from '@angular/core'. constructor() {} ngOnInit() { } } 68 .component. templateUrl: '. Path is the name of the router and component is the name of the class. which in turn has the object of the path and the component.html'.e..component.ts import { Component. styleUrls: ['. Angular 4 export class AppModule { } import { RouterModule} from '@angular/router' Here./new-cmp. the page should display the content. For this. For this.ts as the path. New-cmp. we need the above content from the html file to be displayed whenever required or clicked from the main module. The above tag ensures that the content in the new-cmp.html. 69 . we have created the anchor link tag and given routerLink as “new- cmp”. This is referred in app.<router-outlet> </router-outlet>.component. When a user clicks new component.module.html will be displayed on the page when a user clicks new component. we need to add the router details in the app. Let us now see how the output is displayed on the browser. <h1>Custom Pipe</h1> <b>Square root of 25 is: {{25 | sqrt}}</b><br/> <b>Square root of 729 is: {{729 | sqrt}}</b> <br /> <br /> <br /> <a routerLink = "new-cmp">New component</a> <br /> <br/> <router-outlet></router-outlet> In the above code.html <p> {{newcomponent}} </p> <p> new-cmp works! </p> Now.component. we need the following tag .component. Angular 4 The highlighted class is mentioned in the imports of the main module. 70 . Angular 4 When a user clicks New component. you will see the following in the browser. The feature also gives a good user experience as the page is not reloaded.ts and the router-link in the app.module.html. the new-cmp gets appended to the original url. the page is not refreshed and the contents are shown to the user without any reloading. 71 .component. which is the path given in the app. Angular 4 The url contains http://localhost:4200/new-cmp. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. Here. When a user clicks New component. Only a particular piece of the site code will be reloaded when clicked. etc. To create a service. The command for the same is: C:\projectA4\Angular 4-app>ng g service myservice installing service create src\app\myservice. we will discuss the services in Angular 4.service.service. It can be for data connection that needs to be shared across components. Angular 4 – Services Angular 4 In this chapter. it must be provided to be used C:\projectA4\Angular 4-app> 72 . We might come across a situation where we need some code to be used everywhere on the page. Services help us achieve that.ts create src\app\myservice. 12. we can access methods and properties across other components in the entire project. we need to make use of the command line. With services.spec.ts WARNING Service is generated but not provided. service.service. 73 .myservice. Angular 4 The files are created in the app folder as follows: Following are the files created at the bottom .ts and myservice.ts.specs. /app. Angular 4 myservice. the Injectable module is imported from the @angular/core.module.service'.ts import { Injectable } from '@angular/core'. import { BrowserModule } from '@angular/platform-browser'./app. ChangeTextDirective ].forRoot([ 74 . AppComponent. @NgModule({ declarations: [ SqrtPipe. import { ChangeTextDirective } from '. import { MyserviceService } from './myservice./change-text.component'.directive'. It contains the @Injectable method and a class called MyserviceService.ts. import { RouterModule} from '@angular/router'. We will create our service function in this class.component'. imports: [ BrowserModule. import { AppComponent } from './new-cmp/new-cmp. we need to include the service created in the main parent app. Before creating a new service.service.sqrt'. import { SqrtPipe } from '. import { NgModule } from '@angular/core'. import { NewCmpComponent } from '. NewCmpComponent. RouterModule. @Injectable() export class MyserviceService { constructor() { } } Here. Angular 4 { path: 'new-cmp', component: NewCmpComponent } ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function. In the service class, we will create a function which will display today’s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter. Let us now see how the function looks in the service and how to use it in components. import { Injectable } from '@angular/core'; @Injectable() export class MyserviceService { constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } } In the above service file, we have created a function showTodayDate. Now we will return the new Date () created. Let us see how we can access this function in the component class. 75 Angular 4 app.component.ts import { Component } from '@angular/core'; import { MyserviceService } from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } } The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component ts file. We will display the date in the .html file as shown below: {{todaydate}} <app-new-cmp></app-new-cmp> // data to be displayed to user from the new component class. 76 Angular 4 Let us now see how to use the service in the new component created. import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) export class NewCmpComponent implements OnInit { todaydate; newcomponent = "Entered in new component created"; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } } In the new component that we have created, we need to first import the service that we want and access the methods and properties of the same. Please see the code highlighted. The todaydate is displayed in the component html as follows: <p> {{newcomponent}} </p> <p> Today's Date : {{todaydate}} </p> The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below: 77 Angular 4 If you change the property of the service in any component , the same is changed in other components too. Let us now see how this works. We will define one variable in the service and use it in the parent and the new component. We will again change the property in the parent component and will see if the same is changed in the new component or not. In myservice.service.ts, we have created a property and used the same in other parent and new component. import { Injectable } from '@angular/core'; @Injectable() export class MyserviceService { serviceproperty = "Service Created"; constructor() { } showTodayDate() { let ndate = new Date(); return ndate; } } 78 Angular 4 Let us now use the serviceproperty variable in other components. In app.component.ts, we are accessing the variable as follows: import { Component } from '@angular/core'; import { MyserviceService } from './myservice.ser vice'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; todaydate; componentproperty; constructor(private myservice: Myse rviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); console.log(this.myservice.serviceproperty); this.myservice.serviceproperty = "component created"; // value is changed. this.componentproperty = this.myservice.serviceproperty; } } We will now fetch the variable and work on the console.log. In the next line, we will change the value of the variable to “component created”. We will do the same in new- cmp.component.ts. import { Component, OnInit } from '@angular/core'; import { MyserviceService } from './../myservice.service'; @Component({ selector: 'app-new-cmp', templateUrl: './new-cmp.component.html', styleUrls: ['./new-cmp.component.css'] }) 79 showTodayDate().myservice. Angular 4 export class NewCmpComponent implements OnInit { todaydate. newcomponentproperty.myservice. constructor(private myservice: MyserviceService) { } ngOnInit() { this. Also check the value in the console before it is changed. 80 . we are not changing anything but directly assigning the property to the component property.ts.component. the service property will be changed since the value of it is changed in app. } } In the above component.ts and the same will be displayed for the new- cmp. Now when you execute it in the browser. this.component.todaydate = this. newcomponent = "Entered in newcomponent".newcomponentproperty = this.serviceproperty. To start using the http service. Let us now use the http service in the app. 13.component'. We need to import the http module to make use of the http service. import { AppComponent } from '. etc. import { HttpModule } from '@angular/http'. we need to import the module in app.component. import { Http } from '@angular/http'.ts as shown below: import { BrowserModule } from '@angular/platform-browser'. providers: []. post to it . import { BrowserAnimationsModule } from '@angular/platform -browser/animations'. @NgModule({ declarations: [ AppComponent ]. import 'rxjs/add/operator/map'. import { Component } from '@angular/core'./app.module. imports: [ BrowserModule. we have imported the HttpModule from @angular/htt p and the same is also added in the imports array. Angular 4 – Http Service Angular 4 Http Service will help us fetch external data. Let us consider an example to understand how to make use of the http service. import { NgModule } from '@angular/core'. bootstrap: [AppComponent] }) export class AppModule { } If you see the highlighted code. BrowserAnimationsModule. HttpModule ].ts. 81 . It takes the url to be fetched as the parameter as shown in the code. subscribe( (data) => console. To fetch the data. Two operations are performed on the fetched url data map and subscribe.com/users"). we need to import the same as shown below: import 'rxjs/add/operator/map'. To use the map.css'] }) export class AppComponent { constructor(private http: Http) { } ngOnInit() { this.get(). we need to use the get API available with http as follows: this.get("http://jsonplaceholder.http.log(data) ) } } Let us understand the code highlighted above.component. Angular 4 @Component({ selector: 'app-root'. We will use the test url . We need to import http to make use of the service. The Map method helps to convert the data to json format .typicode.json() ). templateUrl: '.html'.component./app. styleUrls: ['.typicode.com/users to fetch the json data.http./app. 82 . map( (response) => response.http://jsonplaceholder. a constructor is created and the private variable http of type Http. In the class AppComponent. which is done as follows: import { Http } from '@angular/http'. css'] }) export class AppComponent { constructor(private http: Http) { } httpdata. import { Http } from '@angular/http'. update the codes in app.component. The objects can be displayed in the browser too. the subscribe will log the output in the console as shown in the browser: If you see. Angular 4 Once the map is done. styleUrls: ['./app.ts as follows: import { Component } from '@angular/core'.component.html'. 83 . the json objects are displayed in the console. templateUrl: '. import 'rxjs/add/operator/map'./app. For the objects to be displayed in the browser.html and app. @Component({ selector: 'app-root'.component.component. The data is displayed in the browser using for over this httpdata variable. subscribe( (data) => { this. we will store the data in a variable httpdata.ts. "name": "Leanne Graham". In the display data method. "suite": "Apt.com/users"). which is done in the app. using the subscribe method we will call the display data method and pass the data fetched as the parameter to it.biz". "username": "Bret". "city": "Gwenborough". "address": { "street": "Kulas Light".json() ).httpdata = data.name}} Address: {{data. map( (response) => response.html file.city}}</li> </ul> The json object is as follows: { "id": 1. <ul *ngFor = "let data of httpdata"> <li>Name : {{data.address.http. 84 . Angular 4 ngOnInit() { this.typicode. "email": "Sincere@april. } ) } displaydata(data) { this. 556".component.component.displaydata(data). } } In app.get("http://jsonplaceholder. "geo": { "lat": "-37. Angular 4 "zipcode": "92998-3874".1496" } }. "phone": "1-770-736-8031 x56442". and address that internally has street. and other details related to phone.org". "lng": "81.3159". "company": { "name": "Romaguera-Crona". and company. website. Using the for loop. etc. city. "catchPhrase": "Multi-layered client-server neural-net".component. This is how the display is shown in the browser: 85 . email.html file. "website": "hildegard. name. username. we will display the name and the city details in the browser as shown in the app. "bs": "harness real-time e-markets" } } The object has properties such as id. constructor(private http: Http) { } ngOnInit() { this.log(data). styleUrls: ['.component. } } 86 .ts import { Component } from '@angular/core'.searchparam) .converttoarray(data) ) } converttoarray(data) { console.name. Angular 4 Let us now add the search parameter.name = data[0].component.json() ).component. searchparam = 2.html and app. this. jsondata.get("http://jsonplaceholder./app.com/users?id="+this.css'] }) export class AppComponent { title = 'app'. templateUrl: '.typicode. Following are the changes done in app.http. We need to fetch the data based on the search param passed. map( (response) => response. @Component({ selector: 'app-root'./app.ts files: app.component.component. which will filter based on specific data. import 'rxjs/add/operator/map'.html'. import { Http } from '@angular/http'. subscribe( (data) => this. name. Angular 4 For the get api. 87 . The searchparam is equal to 2.searchparam. we will add the search param id = this. The same is displayed in the browser console. The name from the json with id=2 is displayed in the browser.html {{name}} This is how the browser is displayed: We have consoled the data in the browser.component. app. We need the details of id=2 from the json file. which is received from the http. service'. AppComponent. RouterModule. we will see how forms are used in Angular 4./change-text. password and submit the button in the form. We will create a simple login form and add the email id.module./app. import { AppComponent } from '. import { RouterModule} from '@angular/router'. 14. import { HttpModule } from '@angular/http'. We will discuss two ways of working with forms . import { NgModule } from '@angular/core'.component'. imports: [ BrowserModule./app. most of the work is done in the template. FormsModule. ChangeTextDirective ].forRoot([ 88 .component'.directive'. import { MyserviceService } from '. and with the model driven form. @NgModule({ declarations: [ SqrtPipe. import { FormsModule } from '@angular/forms'.template driven form and model driven forms. NewCmpComponent./new-cmp/new-cmp. most of the work is done in the component class./myservice.ts as follows: import { BrowserModule } from '@angular/platform-browser'.sqrt'. Template Driven Form With a template driven form. Angular 4 – Forms Angular 4 In this chapter. HttpModule. we need to import to FormsModule from @angular/core which is done in app. import { ChangeTextDirective } from '. To start with. import { SqrtPipe } from '. import { NewCmpComponent } from '. Let us now consider working on the Template driven form. In template driven forms. component: NewCmpComponent } ]) ]. bootstrap: [AppComponent] }) export class AppModule { } So in app. <form #userlogin="ngForm" (ngSubmit) = "onClickSubmit(userlogin. add ngModel to that tag as shown above.ts. 89 . if we have to read the emailid and passwd.component. we need to add the ngModel across it. Angular 4 { path: 'new-cmp'. If you see. wherever we want Angular to access our data from forms. We have assigned type.html file. name.value to it. we need to create the model form controls by adding the ngModel directive and the name attribute. Thus. The ngForm directive needs to be added to the form template that we have created. and placeholder to it.value)" > <input type="text" name="emailid" placeholder="emailid" ngModel> <br/> <input type="password" name="passwd" placeholder="passwd" ngModel> <br/> <input type="submit" value="submit"> </form> We have created a simple form with input tags having email id. we have also added the ngForm to the #userlogin. Let us now create our form in the app. Now. we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code.module. password and the submit button. We have also added function onClickSubmit and assigned userlogin. providers: [MyserviceService]. When you click on the form submit button.showTodayDate(). Angular 4 Let us now create the function in the app. styleUrls: ['./app.ts and fetch the values entered in the form. import { MyserviceService } from '.emailid).css'] }) export class AppComponent { title = 'Angular 4 Project!'. componentproperty. constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this. templateUrl: '.myservice./myservice.component. @Component({ selector: 'app-root'. import { Component } from '@angular/core'. we have defined the function onClickSubmit. } } In the above app. the control will come to the above function.service'.component. This is how the browser is displayed: 90 . } onClickSubmit(data) { alert("Entered Email id : " + data.component./app.component. todaydate.html'.ts file. 91 . import { SqrtPipe } from './app. NewCmpComponent. import { ReactiveFormsModule } from '@angular/forms'. the email id is already entered.service'. imports: [ BrowserModule.component'. import { AppComponent } from '. import { MyserviceService } from './app. ChangeTextDirective ].component'.directive'. There is a change which goes in app. Let us enter the data in it and in the submit function.ts./new-cmp/new-cmp. Model Driven Form In the model driven form. import { NewCmpComponent } from '. AppComponent./change-text. import { NgModule } from '@angular/core'. import { ChangeTextDirective } from '. import { HttpModule } from '@angular/http'.module. @NgModule({ declarations: [ SqrtPipe. import { RouterModule} from '@angular/router'. we need to import the ReactiveFormsModule from @angular/core and use the same in the imports array. The email id is displayed at the bottom as shown in the above screenshot. HttpModule.sqrt'. Angular 4 The form looks like as shown below. import { BrowserModule } from '@angular/platform-browser'./myservice. For example.component. RouterModule. bootstrap: [AppComponent] }) export class AppModule { } In app. componentproperty.css'] }) export class AppComponent { title = 'Angular 4 Project!'.service'. styleUrls: ['. templateUrl: '.ts. providers: [MyserviceService]./app. component: NewCmpComponent } ]) ]. constructor(private myservice: MyserviceService) { } 92 . import { FormGroup. @Component({ selector: 'app-root'. FormControl } from '@angular/forms'. emailid. import { Component } from '@angular/core'. import { FormGroup.component./app. Angular 4 ReactiveFormsModule. todaydate.forRoot([ { path: 'new-cmp'. formdata. import { MyserviceService } from '. we need to import a few modules for the model driven form.html'./myservice.component. FormControl } from '@angular/forms'. showTodayDate(). This is how the values will be seen in the form UI.emailid.emailid = data.myservice. You can keep it blank in case you want to.com"). <div> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata. passwd: new FormControl("abcd1234") }). } onClickSubmit(data) { this.html.component. The variables emailid and passwd are initialized with default values to be displayed in the form.formdata = new FormGroup({ emailid: new FormControl("
[email protected])" > <input type="text" class="fortextbox" name="emailid" placeholder="emailid" formControlName="emailid"> <br/> <input type="password" class="fortextbox" name="passwd" placeholder="passwd" formControlName="passwd"> <br/> <input type="submit" class="forsubmit" value="Log In"> </form> </div> <p> Email entered is : {{emailid}} 93 . we need to use the same in the form UI app. Angular 4 ngOnInit() { this. } } The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. this.todaydate = this. We have used formdata to initialize the form values. html file. Angular 4 </p> In the . The input tag formControlName is used. For the email id.value is passed.ts file. minlength. the control will pass to the function onClickSubmit. On clicking submit. Let us now try the same on one of the input textboxes.component. the value will be displayed as shown in the above screenshot . We will use both the approaches in the form. we have used formGroup in square bracket for the form. Form Validation Let us now discuss form validation using model driven form. On clicking Login. which is defined in the app. You can use the built-in form validation or also use the custom validation approach. [formGroup]=”formdata”. maxlength. we have added the following validation parameters: Required Pattern matching This is how a code undergoes validation in app.. Validators} from '@angular/forms' Angular has built-in validators such as mandatory field.e. 94 . On submit.component. We will continue with the same example that we created in one of our previous sections. for example. You can just add validators or an array of validators required to tell Angular if a particular field is mandatory. It is given a value that we have used in the app. With Angular 4.ts. email id. the function is called onClickSubmit for which formdata.ts file. These are to be accessed using the Validators module. and pattern.component. i. we need to import Validators from @angular/forms as shown below: import { FormGroup. FormControl. Angular 4 import { Component } from '@angular/core'. styleUrls: ['. componentproperty. Validators. formdata. Right now./app. @Component({ selector: 'app-root'.component. todaydate.compose.component. you can add the list of things you want to validate on the input field.formdata = new FormGroup({ emailid: new FormControl("". templateUrl: '. In the app. the submit button is disabled if any of the form inputs are not valid.css'] }) export class AppComponent { title = 'Angular 4 Project!'.component. emailid. FormControl./app. passwd: new FormControl("") }).html.pattern("[^ @]*@[^ @]*") ])). import { FormGroup.required. Validators.emailid = data. Validators} from '@angular/forms'. ngOnInit() { this. This is done as follows: 95 . } } In Validators. } onClickSubmit(data) { this.compose([ Validators.emailid. we have added the required and the pattern matching parameters to take only valid email.html'. valid. the email id entered is valid. Angular 4 <div> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata. With this. hence the login button is disabled. Let us see the how this works in the browser: In the above case. Thus. the email id entered is displayed at the bottom. which is given value .valid is not valid.!formdata. 96 . we have added disabled in the square bracket. the email id entered is invalid. the button will remain disabled and the user will not be able to submit it. Let us now try entering the valid email id and see the difference. we can see the login button is enabled and the user will be able to submit it. Thus.valid" class="forsubmit" value="Log In"> </form> </div> <p> Email entered is : {{emailid}} </p> For the submit button. if the formdata. Now.value)" > <input type="text" class="fortextbox" name="emailid" placeholder="emailid" formControlName="emailid"> <br/> <input type="password" class="fortextbox" name="passwd" place holder="passwd" formControlName="passwd"> <br/> <input type="submit" [disabled]="!formdata. required./app. todaydate. For custom validation.length < 5) { return {"passwd" : true}. Validators. we can define our own custom function and add the required details in it.passwordvalidation) }). import { Component } from '@angular/core'. @Component({ selector: 'app-root'. Validators} from '@angular/forms'. FormControl.value.component. styleUrls: ['. ngOnInit() { this. this.pattern("[^ @]*@[^ @]*") ])). } } onClickSubmit(data) { 97 . Validators.html'. We will now see an example for the same.formdata = new FormGroup({ emailid: new FormControl("". formdata. passwd: new FormControl("".component.compose([ Validators./app. Angular 4 Let us now try custom validation with the same form. emailid. } passwordvalidation(formcontrol) { if (formcontrol.css'] }) export class AppComponent { title = 'Angular 4 Project!'. templateUrl: '. componentproperty. import { FormGroup. In the function that we have created. } } In the above example. we need more than five characters. If the characters are more than five. it will consider it as valid and the login will be enabled. this. we have created a function password validation and the same is used in a previous section in the formcontrol . 98 .. To enable login. If the characters are less than five.passwd: new FormControl("".passwordvalidation). The login is enabled as both the email id and the password are valid. The email is displayed at the bottom as we log in.return {"passwd" : true}.emailid.emailid = data. Let us now enter a valid length of characters and check. Let us now see how this is displayed in the browser: We have entered only three characters in the password and the login is disabled. it will return with the passwd true as shown above . we will check if the length of the characters entered is appropriate. Angular 4 this. 15.component'.module.module. imports: [ BrowserModule. but is a separate package that needs to be imported in app. To start with. BrowserAnimationsModule ].module. import { NgModule } from '@angular/core'.ts import { BrowserModule } from '@angular/platform-browser'./app. The difference with Angular 4 is that animation is no more a part of the @angular/core library. bootstrap: [AppComponent] }) export class AppModule { } 99 . Angular 4 – Animations Angular 4 Animations add a lot of interaction between the html elements. import { BrowserAnimationsModule } from '@angular/platform -browser/animations'. @NgModule({ declarations: [ AppComponent ]. The BrowserAnimationsModule needs to be added to the import array in app.ts as shown below: app. we need to import the library as follows: import { BrowserAnimationsModule } from '@angular/platform -browser/animations'. Animation was also available with Angular2. import { AppComponent } from '. providers: [].ts. Let us now see the app.style({ 100 . @Component({ selector: 'app-root'. templateUrl: '. transition.component.png" width="100" height="100"></div> </div> For the main div.rotate{ width:100px. text-align: center. <div> <button (click)="animate()">Click Me</button> <div [@myanimation] = "state" class="rotate"><img src="assets/images/img. animations: [ trigger('myanimation'. import { trigger. width:200px. the @myanimation directive is added and given the value as state.[ state('smaller'.component.ts where the animation is defined. state('larger'.style({ transform : 'translateY(100px)' })).css']. style. Angular 4 In app. state.component.html'. animate } from '@angular/animations'.html. we have added the html elements./app. which are to be animated. we have added a button and a div with an image. import { Component } from '@angular/core'. } ./app. styleUrls: ['. styles:[` div{ margin: 0 auto.component. } `]. height:100px. And for the div. There is a click event for which the animate function is called. border:solid 1px red. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied.style({ transform : 'translateY(100 px)' })). we will add the animations property to the @Component () decorator: animations: [ trigger('myanimation'.style({ transform : 'translateY(0px)' })). state. animate() { this.animate('300ms ease-in')) ]) ] Trigger defines the start of the animation. transition('smaller <=> larger'. state.[ state('smaller'. animate } from '@angular/animations'. and animate from @angular/animations. style.state= this. Now.state == 'larger' ? 'smaller' : 'larger'. import { trigger. transition. state('larger'. 101 . style. The second param are the functions we have imported . etc.ts file as shown above.animate('300ms ease-in')) ]) ] }) export class AppComponent { state: string = "smaller". Angular 4 transform : 'translateY(0px)' })). } } We have to import the animation function that is to be used in the . Here we have imported trigger. transition. transition('smaller <=> larger'.state. transition. which the element will transition between. Let us consider the following example to understand the same: styles:[` div{ margin: 0 auto.png" width="100" height="100"></div> </div> There is a style property added in the @component directive. the second argument accepts the animate function. The animate function allows you to define the length. Here.rotate{ width:100px.ts file. } `]. if any. For smaller state. 102 . For the div. text-align: center. Right now we have defined two states. we have given the style transform:translateY(100px) and transform:translateY(0px). a special character [``] is used to add styles to the html element.e. Angular 4 The state function involves the animation steps. which centrally aligns the div. } . smaller and larger. delay. width:200px..component. Let us now see the . height:100px. border:solid 1px red. and easing of a transition. The first argument takes the states. we have given the animation name defined in the app. i. Transition function adds animation to the html element. start and end.html file to see how the transition function works: <div> <button (click)="animate()">Click Me</button> <div [@myanimation] = "state" class="rotate"><img src="assets/images/img. This is how the output in the browser (http://localhost:4200/) will look like: Upon clicking the Click Me button. If the state is larger. Angular 4 On the click of a button it calls the animate function.ts file as follows: export class AppComponent { state: string = "smaller".component. and if smaller. The animate function changes the state on click.state= this.state == ‘larger’? 'smaller' : 'larger'. it will convert to smaller. it will convert to larger. } } The state variable is defined and is given the default value as smaller. which is defined in the app. animate() { this. the position of the image is changed as shown in the following screenshot: 103 . which is changed from 0 to 100px when the Click Me button is clicked. Angular 4 The transform function is applied in the y direction. The image is stored in the assets/images folder. 104 . "@angular/common": "^4. 16. npm install --save @angular/material @angular/cdk Let us now see the package.0.0". Angular 2 also has all the above features but they are available as part of the @angular/core module. "version": "0. datepicker. grids. "dependencies": { "@angular/animations": "^4. slider. "@angular/core": "^4. "@angular/forms": "^4. @angular/material and @angular/cdk are installed. "private": true. @angular/animations. The package has already been updated in the previous chapter. and toolbar are available for use with materials in Angular 4.json.0". 105 .0. "e2e": "ng e2e" }. we need to import the package. "license": "MIT".0. Features such as autocomplete.e. "start": "ng serve".8". menus. Angular 4 – Materials Angular 4 Materials offer a lot of built-in modules for your project. i. "test": "ng test". To start using materials. Angular 4 has come up with a separate module @angular/materials. Material components depend on the animation module for advanced features. "@angular/cdk": "^2.0. "build": "ng build".0". { "name": "angularstart".materials and cdk.0".0-beta. "lint": "ng lint". hence you need the animation package for the same.. To use materials.0.0.0". "scripts": { "ng": "ng".0. This helps the user to import the required materials. "@angular/compiler": "^4.0". you need to install two packages . 2.0". "@angular/material": "^2.0.0-beta. "@angular/router": "^4.0".1. "karma-coverage-istanbul-reporter": "^1.0.0. "codelyzer": "~3.1. "core-js": "^2.0".0".0. "karma-jasmine-html-reporter": "^0.0.0.8".60". "jasmine-spec-reporter": "~4.53". Angular 4 "@angular/http": "^4. "@angular/language-service": "^4.1".1". "karma-chrome-launcher": "~2. "karma-cli": "~1.2. "@angular/compiler-cli": "^4.2".0.1".5. "rxjs": "^5.0.1.8.6.0". "karma": "~1.4.3.2". "@types/node": "~6. "typescript": "~2.0".2".js": "^0.1.2". "devDependencies": { "@angular/cli": "1. "zone.0. "@types/jasminewd2": "~2. 106 .1".0". "@angular/platform-browser-dynamic": "^4.0". "karma-jasmine": "~1.3.2.0.0.0".1". "ts-node": "~3.4" }. "protractor": "~5.4". "@angular/platform-browser": "^4.0.1.2". "jasmine-core": "~2.0".3" } } We have highlighted the packages that are installed to work with materials. "tslint": "~5.7. "@types/jasmine": "~2.0". import { BrowserAnimationsModule } from '@angular/platform -browser/animations'. imports: [ BrowserModule. import { BrowserModule } from '@angular/platform-browser'. MdSidenavModule } from '@angular/material'. @NgModule({ declarations: [ AppComponent ]. FormsModule. Angular 4 We will now import the modules in the parent module . import { FormsModule } from '@angular/forms'. we have imported the following modules from @angular/materials. MdButtonModule.module. import { MdButtonModule. MdSidenavModule ]. BrowserAnimationsModule. MdMenuModule. import { MdButtonModule. MdSidenavModule } from '@angular/material'.app. MdMenuModule.component'. import { NgModule } from '@angular/core'. bootstrap: [AppComponent] }) export class AppModule { } In the above file.ts as shown below. 107 . MdMenuModule. providers: []./app. import { AppComponent } from '. /app. @Component({ selector: 'app-root'. <button md-button [mdMenuTriggerFor]="menu">Menu</button> <md-menu #menu="mdMenu"> <button md-menu-item>File</button> <button md-menu-item>Save As</button> </md-menu> 108 . Angular 4 And the same is used in the imports array as shown below: imports: [ BrowserModule.ts is as shown below: import { Component } from '@angular/core'. MdButtonModule. constructor() { } } Let us now add the material in app.css'] }) export class AppComponent { myData: Array<any>. MdMenuModule.html. MdSidenavModule ] The app.html'.component.component. FormsModule. templateUrl: '.component. BrowserAnimationsModule.component./app. styleUrls: ['. SideNav To add sidenav.open()"> Open sidenav </button> </div> </md-sidenav-container> In the above file.menu> by using [mdMenuTrigge rFor]=”me nu” and using the menu with # in <md-menu>. <md- sidenav></md-sidenav> is added as a child to the container. Following is the display of the menu and the sidenav in the browser: 109 . <md-menu></md-menu> is used. There is a main button added Menu. The reference of the same is given the <md. we have added Menu and SideNav. Angular 4 <md-sidenav-container class="example-container"> <md-sidenav #sidenav class="example -sidenav"> Angular 4 </md-sidenav> <div class="example-sidenav-content"> <button type="button" md -button (click)="sidenav. which triggers the sidenav by using (click)=”sidenav. The file and Save As items are added to the button under md-menu. Menu To add menu. There is another div added. we need <md-sidenav-container></md-sidenav-containe r>.open()”. it shows the side bar as shown below: 110 . Angular 4 Upon clicking opensidenav. module. import { AppComponent } from '. we need to import the modules required to show the datepicker./app. To add a datepicker. In app.component'. MdInputModule. import { BrowserAnimation sModule } from '@angular/platform -browser/animations'. @NgModule({ declarations: [ AppComponent ].ts. imports: [ BrowserModule. import { NgModule } from '@angular/core'. BrowserAnimationsModule. Angular 4 Upon clicking Menu. 111 . MdNativeDateModule } from '@angular/material'. import { MdDatepickerModule. import { FormsModule } from '@angular/forms'. we have imported the following module as shown below for dat epicker. import { BrowserModule } from '@angular/platform-browser'. you will get two items File and Save As as shown below: Let us now add a datepicker using materials. providers: []. and MdNativeDateModule. Angular 4 FormsModule. the app. MdDatepickerModule.component. MdInputModule. constructor() { } } 112 . we have imported modules such as MdDatepickerModule.component. templateUrl: '.component. Now./app. styleUrls: ['.css'] }) export class AppComponent { myData: Array<any>.ts is as shown below: import { Component } from '@angular/core'. @Component({ selector: 'app-root'.html'. MdNativeDateModule ]./app. MdInputModule. bootstrap: [AppComponent] }) export class AppModule { } Here. Angular 4 The app.component.html is as shown below: <md-input-container> <input mdInput [mdDatepicker]="picker" placeholder="Choose a date"> <button mdSuffix [mdDatepickerToggle]="picker"></button> </md-input-container> <md-datepicker #picker></md-datepicker> This is how the datepicker is displayed in the browser: 113 . Component ng g component new-component Directive ng g directive new-directive Pipe ng g pipe new-pipe Service ng g service new-service Module ng g module my-module Whenever a new module. 114 . a component and services. we can run the following command in the command line and the project will be created.ts. or a service is created. change the port . To work with Angular CLI. ng new PROJECT-NAME cd PROJECT-NAME ng serve // ng serve // will compile and you can see the output of your project in the browser: http://localhost:4200/ 4200 is the default port used when a new project is created. Angular 4 – CLI Angular 4 Angular CLI makes it easy to start with any Angular project. etc.0. we need to have it installed on our system. Let us now go through the commands available to create a project.module. 17.0 --port 4201 The following table lists down a few important commands required while working with Angular 4 projects. the reference of the same is updated in the parent module app.0. Angular CLI comes with commands that help us create and start on our project very fast. You can change the port with the following command: ng serve --host 0. Let us use the following command for the same: npm install -g @angular/cli To create a new project. a component. spec.html create src\app\footer\footer.header.module.component. we will discuss a few examples related to Angular 4.css create src\app\header\header. userlogin and mainpage.component. you can enter the customer details.css create src\app\footer\footer. Angular 4 – Examples Angular 4 In this chapter.ts update src\app\app.html create src\app\header\header. we have created an example which shows a login form with input as username and password. To begin with.component.spec.css create src\app\userlogin\userlogin. In addition. it will enter inside and show another form wherein. footer.component. Upon entering the correct values.component.component.ts create src\app\footer\footer.ts create src\app\header\header.module.ts 115 .ts update src\app\app.component.ts ng g component footer C:\ngexamples\aexamples>ng g component footer installing component create src\app\footer\footer. The components are created using the following command: ng g component header C:\ngexamples\aexamples>ng g component header installing component create src\app\header\header.component.component.ts ng g component userlogin C:\ngexamples\aexamples>ng g component userlogin installing component create src\app\userlogin\userlogin. 18.component. we have created four components .html create src\app\userlogin\userlogin.component.spec. /mainpage/mainpage.spec. import { ReactiveFormsModule } from '@angular/forms'.component'.ts create src\app\mainpage\mainpage. const appRoutes: Routes = [ { path: ''./userlogin/userlogin. the parent module has all the components added when created.html create src\app\mainpage\mainpage. component: UserloginComponent }. { 116 .ts In the app.css create src\app\mainpage\mainpage.component. import { BrowserAnimationsModule } from '@angular/platform -browser/animations'. import {MdInputModule} from '@angular/material'.module.module.component. import { UserloginComponent } from './footer/footer.component.component'.ts update src\app\app. import { RouterModule.ts.ts update src\app\app. import { AppComponent } from './app. import { FooterComponent } from '. import { HeaderComponent } from '. import { MainpageComponent } from '. import {HttpModule} from "@angular/http".component'.component'. import { NgModule } from '@angular/core'.component.module. Angular 4 create src\app\userlogin\userlogin.component.component'.ts ng g component mainpage C:\ngexamples\aexamples>ng g component mainpage installing component create src\app\mainpage\mainpage. The file looks as follows: import { BrowserModule } from '@angular/platform-browser'. import {MdTableModule} from '@angular/material'./header/header. Routes} froms '@angular/router'. Angular 4 path: 'app-mainpage'./userlogin/userlogin. MdTableModule. component: MainpageComponent } ]. ReactiveFormsModule.component'.forRoot(appRoutes). FooterComponent. HeaderComponent./header/header. UserloginComponent. import { FooterComponent } from '. MainpageComponent ]./footer/footer. BrowserAnimationsModule.component'. import { UserloginComponent } from '. MdInputModule ]. 117 . RouterModule. imports: [ BrowserModule. providers: []. bootstrap: [AppComponent] }) export class AppModule { } The components created above are added: import { HeaderComponent } from '. HttpModule.component'. import { MainpageComponent } from '.component'. @NgModule({ declarations: [ AppComponent./mainpage/mainpage. import { MainpageComponent } from '. The <router-outlet></route r-outlet> is used for navigation between one page to another. <div class="mainpage"> <app-header></app-header> <router-outlet></router-outlet> <app-footer></app-footer> </div> We have created a div and added <app-header></app-header>./footer/footer. 118 . import { AppComponent } from '. Angular 4 The components are added in the declarations too: declarations: [ AppComponent. import { BrowserAnimationsModule } from '@angular/platform -browser/animations'. In the parent app. import {HttpModule} from "@angular/http". import { HeaderComponent } from '. import { FooterComponent } from './userlogin/userlogin. the changes are done in app.component'./mainpage/mainpage. Here. HeaderComponent. To get the login-form first and later get the mainpage. MainpageComponent ]. import { RouterModule. import {MdInputModule} from '@angular/material'.c omponent. we have added the main structure of the file that will be seen by the user. the pages are login-form and once it is successful it will redirect to the mainpage.html.component'./header/header. i. <router- outlet></router-outlet> and <app-footer></app-footer>. the customer form.html. import { ReactiveFormsModule } from '@angular/forms'. import { UserloginComponent } from '.e.component'. import { NgModule } from '@angular/core'. Routes} from '@angular/router'.module.component'../app. import {MdTableModule} from '@angular/material'.component.component'.ts as shown below: import { BrowserModule } from '@angular/platform-browser'. UserloginComponent. FooterComponent. RouterModule. HttpModule. HeaderComponent. MdTableModule. { path: 'app-mainpage'. component: MainpageComponent } ].forRoot(appRoutes). BrowserAnimationsModule. MdInputModule ]. providers: []. Angular 4 const appRoutes: Routes = [ { path: ''. FooterComponent. @NgModule({ declarations: [ AppComponent. bootstrap: [AppComponent] }) export class AppModule { } 119 . MainpageComponent ]. component: UserloginComponent }. ReactiveFormsModule. UserloginComponent. imports: [ BrowserModule. Routes take the array of components and by default the userloginComponent is called. } 120 .minLength(6) ])). this. Validators.passwordvalidation) }). passwd: new FormControl("". import { FormGroup. @Component({ selector: 'app-userlogin'.component. templateUrl: '. OnInit } from '@angular/core'. Angular 4 We have imported RouterModule and Routes from @anuglar/router. In imports./userlogin. { path: 'app-mainpage'.component.component. import { Router} from '@angular/router'.compose([ Validators.ts. Validators. styleUrls: ['. we have imported the router and navigated to mainpage. component: UserloginComponent }. the RouterModules takes appRoutes as the param which is defined above as: const appRoutes: Routes = [ { path: ''.css'] }) export class UserloginComponent implements OnInit { formdata./userlogin.component.required.ht ml based on the condition as shown below: import { Component. Validators} from '@angular/forms'.html'. In userlogin. constructor(private router: Router) { } ngOnInit() { this. FormControl.formdata = new FormGroup({ uname: new FormControl("". component: MainpageComponent } ]. } } onClickSubmit(data) { console.navigate(['app-mainpage']) } else { alert("Invalid Login"). return false. templateUrl: '.uname)./app. Angular 4 passwordvalidation(formcontrol) { if (formcontrol./app.html'.router. Only the default details are present in it. this.css'] }) export class AppComponent { title = 'app'.passwd=="admin123") { alert("Login Successful").length < 5) { return {"passwd" : true}.ts file for app. } } } Following is the . if (data.uname=="systemadmin" && data.component. @Component({ selector: 'app-root'.ts.component.log(data. import { Component } from '@angular/core'.value.component. } 121 . styleUrls: ['. html.component.component.component. To start with.component.component.spec.html. templateUrl: '.component.component. This makes the header. Angular 4 Let us now display the details of each of the components files.ts and footer.html <div > <hr /> </div> We have not added any css.css file empty.component. we will draw a horizontal line. For the footer component. footer.ts. footer./header.component.component.spec.spec. header. footer.component. A logo or any other detail can be added to make the header look more creative.css'] }) export class HeaderComponent implements OnInit { constructor() { } ngOnInit() { } } header. the header.ts file is empty as the test cases are not considered here. Let us now consider creating a footer component .css. we will first take the header component. For the header. styleUrls: ['.compoent.component. header./header. four files are created header. @Component({ selector: 'app-header'.ht ml'. and header. Also.ts import { Component.ts.component. 122 . header.ts.css files are created. For the new component. OnInit } from '@angular/core'. Also. templateUrl: '.component. Let us now see how the userlogin component works. and userlogin.component.ts. we will just draw a horizontal line as shown in the .component.html <div class="form_container"> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata. userlogin.compoent. The details of the files are as follows: userlogin.html file.component.html <hr/> As we have not added any css. Angular 4 footer.ts file is empty as the test cases are not considered here. userlogin. The following files for userlogin component created are userlogin.spec.component.component.css file is empty.css'] }) export class FooterComponent implements OnInit { constructor() { } ngOnInit() { } } footer. the footer.css.component. @Component({ selector: 'app-footer'./footer.ts.value)" > <header>Login</header> <label>Username <span>*</span></label> <input type="text" name="uname" formControlName="uname"/> <div class="help">At least 6 character</div> <label>Password <span>*</span></label> 123 . OnInit } from '@angular/core'. the footer. styleUrls: ['./footer.spec.html.ts import { Component.component.component. For the footer.html'.component. passwordvalidation) }). we have created form with two input controls Username and Password. @Component({ selector: 'app-userlogin'. styleUrls: ['.required. We consider the username and password mandatory. the control is passed to the onClickSubmit.component. userlogin./userlogin./userlogin.css'] }) export class UserloginComponent implements OnInit { formdata. templateUrl: '. Validators. hence the validation for the same is added in the ts. Upon clicking the submit button. FormControl. import { FormGroup.compose([ Validators. import { Router} from '@angular/router'. which is defined in the ts file. Angular 4 <input type="password" class="fortextbox" name="passwd" formControlName="passwd"/> <div class="help">Use upper and lowercase lettes as well</div> <button [disabled]="!formdata. } passwordvalidation(formcontrol) { 124 .formdata = new FormGroup({ uname: new FormControl("". this.component.ts import { Component.valid" value="Login">Login</button> </form> </div> Here.html'. Validators.minLength(6) ])).component. passwd: new FormControl("". Validators} from '@angular/forms'. OnInit } from '@angular/core'. constructor(private router: Router) { } ngOnInit() { this. This is a model driven form approach and the details of the same are explained in Chapter 14 - Forms. value. Angular 4 if (formcontrol. We need a router to navigate to a different component when the user and password are correct. In ngOnInit. 125 . a dialog box appears that shows Login Successful and the router navigates to the app-mainpage. this. } } onClickSubmit(data) { console. if (data. Upon clicking submit.router. the validation for the form is done. the modules are imported as shown below: import { FormGroup. If yes.passwd=="admin123") { alert("Login Successful").uname=="systemadmin" && data. There is css added for the form in userlogin. } form { background: white. width: 500px.uname).form_container{ margin : 0 auto. We need the username to be more than six characters and the field is mandatory. width:600px.length < 5) { return {"passwd" : true}.component.log(data. The same condition applies to password too. For this. we can check if the username is systemadmin and the password is admin123. FormControl. the router is imported as shown below: import { Router} from '@angular/router'.css file: . which is the selector of the mainpage component.navigate(['app-mainpage']) } } } For the formcontrol and validation. Validators} from '@angular/forms'. position: absolute.3em. Angular 4 box-shadow: 0px 0px 20px rgba(0. font-weight: 600. position: relative. color: #333. left: 2. padding: 30px 20px. margin-top: 30px. margin-left: 20px.2em. padding: 5px 20px. top: -10px. 126 . } form label span { color: #FF3838. } form label { margin-left: 20px. font-size: 2em. font-size: 1. margin-bottom: 5px. } form input { display: block. } form header { background: #FF3838. font-size: 1em. border: 1px solid #ccc. color: white. 0. width: 50%. 0. border-radius: 10px. font-family: lato. border-radius: 10px 10px 0 0. outline: none. 0. border-radius: 3px.7). display: inline-block. position: relative. color: white. 51. font-size: 0. color: #777. font-weight: 400. border-radius: 3px. 51. font-family: inherit.8em. } The userlogin. } form button { position: relative. background: #FF3838. left: 50%.component.help { margin-left: 20px. 127 . transform: translate(-50%.spec. margin-top: 30px. 0). border: none. } form button:hover { background: #ff5252. margin-bottom: 30px.15s ease-in-out.ts file is empty as there no test cases right now. 0. Angular 4 } form . font-size: 1. padding: 5px 15px. cursor: pointer.3em.4). box-shadow: 0px 0px 10px rgba(51. transition: all 0. outline: none. lname: new FormControl("". Validators.ts.css. styleUrls: ['. import 'rxjs/add/operator/map'. address:new FormControl(""). Response. ViewChild} from '@angular/core'.formdata = new FormGroup({ fname: new FormControl("". constructor(private http: Http) { } stateCtrl: FormControl. and mainpage. FormControl. templateUrl: '. mainpage.compose([ Validators. mainpage.html'.ts import { Component.spect.minLength(3) ])).required.component.component. @Component({ selector: 'app-mainpage'. } 128 .html.component.component. mainpage. cutomerdata.compose([ Validators./mainpage. OnInit.component. Headers. Validators. Angular 4 Let us now discuss how the mainpage component works. phoneno:new FormControl("") }). import { FormGroup.ts. Validators} from '@angular/forms'.required. import {Http. Validators./mainpage.component. ngOnInit() { this. RequestOptions } from "@angular/http".minLength(3) ])). Validators.component.css'] }) export class MainpageComponent implements OnInit { formdata. The files created for mainpage component are mainpage. style.html file as shown below. address and phone number.component."> <table> <tr> <td>FirstName</td> 129 . this.log(this. which is done in the . Angular 4 onClickSubmit(data) { document. Upon clicking submit. the table which is used to display the entered details is made visible. mainpage. for (var prop in data) { this.display="". The validation of the same is done with the ngOnInit function.cutomerdata = [].valid" value="Submit">Submit</button> </form> </div> <br/> <div id="custtable" style="display:none. } } We have created a customer form with firstname. lastname .cutomerdata. Here.cutomerdata).margin:0 auto. the control comes to the function onClickSubmit.getElementById("custtable"). The customerdata is converted from json to array so that we can use the same in ngFor on the table.value)" > <header>Customer Details</header> <label>FirstName <span>*</span></label> <input type="text" name="fname" formControlName="fname"/> <label>LastName <span>*</span></label> <input type="text" name="lname" formControlName="lname"/> <label>Address <span></span></label> <input type="text" name="address" formControlName="address"/> <label>Phone No <span></span></label> <input type="text" name="phoneno" formControlName= "phoneno"/> <button [disabled]="!formdata.push(data[prop]). } console.html <div class="form_container"> <form [formGroup]="formdata" (ngSubmit) = "onClickSubmit(formdata. the first div has the customer details and the second div has the table . This is the page with login form and header and footer. Angular 4 <td>LastName</td> <td>Address</td> <td>Phone No</td> </tr> <tr><td *ngFor="let data of cutomerdata"><h5>{{data}}</h5></td></tr> </table> </div> Here. The display of the userlogin and the customer details is as shown below. which will show the entered details. 130 . 131 . the display is as shown below: Upon clicking submit. Angular 4 Once you enter the details. a dialog box appears which shows Login Successful. Angular 4 If the details are invalid. a dialog box appears which shows Invalid Login as shown below: If the login is successful. it will proceed to the next form of Customer Details as shown below: 132 . a dialog box appears which shows the Customer Details are added as shown in the screenshot below: When we click OK in the above screenshot. Angular 4 Once the details are entered and submitted. the details will appear as shown in the screenshot below: 133 .