Angular 4 – Examples ”; Previous Next In this chapter, we will discuss a few examples related to Angular 4. To begin with, we have created an example which shows a login form with input as username and password. Upon entering the correct values, it will enter inside and show another form wherein, you can enter the customer details. In addition, we have created four components – header, footer, userlogin and mainpage. The components are created using the following command − ng g component header C:ngexamplesaexamples>ng g component header installing component create srcappheaderheader.component.css create srcappheaderheader.component.html create srcappheaderheader.component.spec.ts create srcappheaderheader.component.ts update srcappapp.module.ts ng g component footer C:ngexamplesaexamples>ng g component footer installing component create srcappfooterfooter.component.css create srcappfooterfooter.component.html create srcappfooterfooter.component.spec.ts create srcappfooterfooter.component.ts update srcappapp.module.ts ng g component userlogin C:ngexamplesaexamples>ng g component userlogin installing component create srcappuserloginuserlogin.component.css create srcappuserloginuserlogin.component.html create srcappuserloginuserlogin.component.spec.ts create srcappuserloginuserlogin.component.ts update srcappapp.module.ts ng g component mainpage C:ngexamplesaexamples>ng g component mainpage installing component create srcappmainpagemainpage.component.css create srcappmainpagemainpage.component.html create srcappmainpagemainpage.component.spec.ts create srcappmainpagemainpage.component.ts update srcappapp.module.ts In the app.module.ts, the parent module has all the components added when created. The file looks as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { ReactiveFormsModule } from ”@angular/forms”; import { RouterModule, Routes} froms ”@angular/router”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import {MdTableModule} from ”@angular/material”; import {HttpModule} from “@angular/http”; import {MdInputModule} from ”@angular/material”; import { AppComponent } from ”./app.component”; import { HeaderComponent } from ”./header/header.component”; import { FooterComponent } from ”./footer/footer.component”; import { UserloginComponent } from ”./userlogin/userlogin.component”; import { MainpageComponent } from ”./mainpage/mainpage.component”; const appRoutes: Routes = [ { path: ””, component: UserloginComponent }, { path: ”app-mainpage”, component: MainpageComponent } ]; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), BrowserAnimationsModule, HttpModule, MdTableModule, MdInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The components created above are added − import { HeaderComponent } from ”./header/header.component”; import { FooterComponent } from ”./footer/footer.component”; import { UserloginComponent } from ”./userlogin/userlogin.component”; import { MainpageComponent } from ”./mainpage/mainpage.component”; The components are added in the declarations too − declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], In the parent app.component.html, we have added the main structure of the file that will be seen by the user. <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>, <router-outlet></router-outlet> and <app-footer></app-footer>. The <router-outlet></router-outlet> is used for navigation between one page to another. Here, the pages are login-form and once it is successful it will redirect to the mainpage, i.e., the customer form. To get the login-form first and later get the mainpage.component.html, the changes are done in app.module.ts as shown below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { ReactiveFormsModule } from ”@angular/forms”; import { RouterModule, Routes} from ”@angular/router”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import {MdTableModule} from ”@angular/material”; import {HttpModule} from “@angular/http”; import {MdInputModule} from ”@angular/material”; import { AppComponent } from ”./app.component”; import { HeaderComponent } from ”./header/header.component”; import { FooterComponent } from ”./footer/footer.component”; import { UserloginComponent } from ”./userlogin/userlogin.component”; import { MainpageComponent } from ”./mainpage/mainpage.component”; const appRoutes: Routes = [ { path: ””, component: UserloginComponent }, { path: ”app-mainpage”, component: MainpageComponent } ]; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, UserloginComponent, MainpageComponent ], imports: [ BrowserModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes), BrowserAnimationsModule, HttpModule, MdTableModule, MdInputModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } We have imported RouterModule and Routes from @anuglar/router. In imports, the RouterModules takes appRoutes as the param which is defined above as − const appRoutes: Routes = [ { path: ””, component: UserloginComponent }, { path: ”app-mainpage”, component: MainpageComponent } ]; Routes take the array of components and by default the userloginComponent is called. In userlogin.component.ts, we have imported the router and navigated to mainpage.component.html based on the condition as shown below − import { Component, OnInit } from ”@angular/core”; import { FormGroup, FormControl, Validators} from ”@angular/forms”; import { Router} from ”@angular/router”; @Component({ selector: ”app-userlogin”, templateUrl: ”./userlogin.component.html”, styleUrls: [”./userlogin.component.css”] }) export class UserloginComponent implements OnInit { formdata; constructor(private router: Router) { } ngOnInit() { this.formdata = new FormGroup({ uname: new FormControl(“”, Validators.compose([ Validators.required, Validators.minLength(6) ])), passwd: new FormControl(“”, this.passwordvalidation) }); } passwordvalidation(formcontrol) { if (formcontrol.value.length < 5) { return {“passwd” : true}; } } onClickSubmit(data) { console.log(data.uname); if (data.uname==”systemadmin” && data.passwd==”admin123″) { alert(“Login Successful”); this.router.navigate([”app-mainpage”]) } else { alert(“Invalid Login”); return false; } } } Following is the .ts file for app.component.ts. Only the default details are present in it. import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent {title = ”app”;} Let us now display the details of each of the components files. To start with, we will first take the header component. For the new component, four files are created header.component.ts, header.component.html, header.component.css, and header.component.spec.ts. header.component.ts import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-header”, templateUrl: ”./header.component.html”, styleUrls: [”./header.component.css”] }) export class HeaderComponent implements OnInit { constructor() { } ngOnInit() {} } header.component.html <div> <hr /> </div> We have not added any css. This makes the header.component.css file empty. Also, the header.compoent.spec.ts file is empty as the test cases are not considered here. For the header, we will draw a horizontal line. A logo or any other detail can be added to make the header look more creative. Let us now consider creating a footer component. For the footer component, footer.component.ts, footer.component.html, footer.component.spec.ts and footer.component.css files are created. footer.component.ts import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-footer”, templateUrl: ”./footer.component.html”, styleUrls: [”./footer.component.css”] }) export class FooterComponent implements OnInit { constructor() { } ngOnInit() { } } footer.component.html <hr/> As we have not added any css, the footer.component.css file is empty. Also, the footer.compoent.spec.ts file is empty as the test cases are not considered here. For the footer, we will just draw a horizontal line as shown in the .html file. Let us now see how the userlogin component works. The following files for userlogin component created are userlogin.component.css, userlogin.component.html, userlogin.component.ts, and userlogin.component.spec.ts. The details of the files are as follows
Category: angular4
Angular 4 – Project Setup
Angular 4 – Project Setup ”; Previous Next AngularJS is based on the model view controller, whereas Angular 2 is based on the components structure. Angular 4 works on the same structure as Angular2 but is faster when compared to Angular2. Angular4 uses TypeScript 2.2 version whereas Angular 2 uses TypeScript version 1.8. This brings a lot of difference in the performance. To install Angular 4, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 4. Go to this site https://cli.angular.io to install Angular CLI. To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest version. The npm package gets installed along with nodejs. Go to the nodejs site https://nodejs.org/en/. The latest version of Nodejs v6.11.0 is recommended for users. Users who already have nodejs greater than 4 can skip the above process. Once nodejs is installed, you can check the version of node in the command line using the command, node –v, as shown below − The command prompt shows v6.11.0. Once nodejs is installed, npm will also get installed along with it. To check the version of npm, type command npm –v in the terminal. It will display the version of npm as shown below. The version of npm is 3.10.10. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 4. 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 Let us start with the first command in the command line and see how it works. To start with, we will create an empty directory wherein, we will run the Angular CLI command. Enter the above command to install Angular 4. The installation process will start and will take a few minutes to complete. Once the above command to install is complete, the following Command Prompt appears − We have created an empty folder ProjectA4 and installed the Angular CLI command. We have also used -g to install Angular CLI globally. Now, you can create your Angular 4 project in any directory or folder and you don’t have to install Angular CLI project wise, as it is installed on your system globally and you can make use of it from any directory. Let us now check whether Angular CLI is installed or not. To check the installation, run the following command in the terminal − ng -v We get the @angular/cli version, which is at present 1.2.0. The node version running is 6.11.0 and also the OS details. The above details tell us that we have installed angular cli successfully and now we are ready to commence with our project. We have now installed Angular 4. Let us now create our first project in Angular 4. To create a project in Angular 4, we will use the following command − ng new projectname We will name the project ng new Angular 4-app. Let us now run the above command in the command line. The project Angular 4-app is created successfully. It installs all the required packages necessary for our project to run in Angular 4. Let us now switch to the project created, which is in the directory Angular 4-app. Change the directory in the command line – cd Angular 4-app. We will use Visual Studio Code IDE for working with Angular 4; you can use any IDE, i.e., Atom, WebStorm, etc. To download Visual Studio Code, go to https://code.visualstudio.com/ and click Download for Windows. Click Download for Windows for installing the IDE and run the setup to start using IDE. The Editor looks as follows − We have not started any project in it. Let us now take the project we have created using angular-cli. We will consider the Angular 4-app project. Let us open the Angular 4-app and see how the folder structure looks like. Now that we have the file structure for our project, let us compile our project with the following command − ng serve The ng serve command builds the application and starts the web server. 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, you will receive the following output − Once you run http://localhost:4200/ in the browser, 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.component.html and app.component.ts. We will discuss more about this in our subsequent chapters. Let us complete the project setup. If you see we have used port 4200, which is the default port that angular–cli makes use of while compiling. You can change the port if you wish using the following command − ng serve –host 0.0.0.0 –port 4205 The Angular 4 app folder has the following folder structure − e2e − end to end test folder. Mainly e2e is used for integration testing and helps ensure the application works fine. node_modules − The npm package installed is node_modules. You can open the folder and see the packages available. src − This folder is where we will work on the project using Angular 4. The Angular 4 app folder has the following file structure − .angular-cli.json − It basically holds the project name, version of cli, etc. .editorconfig − This is the config file for the editor. .gitignore − A .gitignore file should be committed into the repository, in order to share the ignore rules with any other users that clone the repository. karma.conf.js − This is used for unit testing via the protractor. All the information required for the project is provided in karma.conf.js file. package.json − The package.json file tells which libraries will be
Angular 4 – Quick Guide
Angular 4 – Quick Guide ”; Previous Next Angular 4 – Overview There are three major releases of Angular. The first version that was released is Angular1, which is also called AngularJS. Angular1 was followed by Angular2, which came in with a lot of changes when compared to Angular1. The structure of Angular is based on the components/services architecture. AngularJS was based on the model view controller. 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 is almost the same as Angular 2. It has a backward compatibility with Angular 2. Projects developed in Angular 2 will work without any issues with Angular 4. Let us now see the new features and the changes made in Angular 4. 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. Let us now see the new features added to Angular 4 − ngIf Angular2 supported only the if condition. However, Angular 4 supports the if else condition as well. Let us see how it works using the ng-template. <span *ngIf=”isavailable; else condition1″>Condition is valid.</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.length}} </div> The variable total stores the output of the slice using the as keyword. Animation Package Animation in Angular 4 is available as a separate package and needs to be imported from @angular/animations. In Angular2, it was available with @angular/core. It is still kept the same for its backward compatibility aspect. Template Angular 4 uses <ng-template> as the tag instead of <template>; the latter was used in Angular2. 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. It will deprecate completely going ahead. This is one of the major changes in Angular 4. TypeScript 2.2 Angular 4 is updated to a recent version of TypeScript, which is 2.2. This helps improve the speed and gives better type checking in the project. Pipe Title Case Angular 4 has added a new pipe title case, which changes the first letter of each word into uppercase. <div> <h2>{{ ”Angular 4 titlecase” | titlecase }}</h2> </div> The above line of code generates the following output – Angular 4 Titlecase. Http Search Parameters Search parameters to the http get api is simplified. We do not need to call URLSearchParams for the same as was being done in Angular2. Smaller and Faster Apps Angular 4 applications are smaller and faster when compared to Angular2. It uses the TypeScript version 2.2, the latest version which makes the final compilation small in size. Angular 4 – Environment Setup In this chapter, we will discuss the Environment Setup required for Angular 4. To install Angular 4, 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. Nodejs To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system. C:>node –v v6.11.0 If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The homepage of nodejs will look like the following − Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm. C:>npm –v 5.3.0 Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command. Type npm install –g @angular/cli, to install angular cli on your system. You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc. The details of the project setup is explained in the next chapter. Angular 4 – Project Setup AngularJS is based on the model view controller, whereas Angular 2 is based on the components structure. Angular 4 works on the same structure as Angular2 but is faster when compared to Angular2. Angular4 uses TypeScript 2.2 version whereas Angular 2 uses TypeScript version 1.8. This brings a lot of difference in the performance. To install Angular 4, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 4. Go to this site https://cli.angular.io to install Angular CLI. To get started with the installation, we first need to make sure we have nodejs and npm installed with the latest version. The npm package gets installed along with nodejs. Go to the nodejs site https://nodejs.org/en/. The latest version of Nodejs v6.11.0 is recommended for users. Users who already have nodejs greater than 4 can skip the above process. Once nodejs is installed, you can check the version of node in the command line using the command, node –v, as shown below − The command prompt shows v6.11.0. Once nodejs is installed, npm will also get installed along with it. To check the version of npm, type command npm –v in the terminal. It will display the version of npm as shown below. The version of npm is 3.10.10. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 4. You will see the following commands on the webpage − npm install -g @angular/cli //command to
Angular 4 – Services
Angular 4 – Services ”; Previous Next In this chapter, we will discuss the services in Angular 4. We might come across a situation where we need some code to be used everywhere on the page. It can be for data connection that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project. To create a service, we need to make use of the command line. The command for the same is − C:projectA4Angular 4-app>ng g service myservice installing service create srcappmyservice.service.spec.ts create srcappmyservice.service.ts WARNING Service is generated but not provided, it must be provided to be used C:projectA4Angular 4-app> The files are created in the app folder as follows − Following are the files created at the bottom – myservice.service.specs.ts and myservice.service.ts. myservice.service.ts import { Injectable } from ”@angular/core”; @Injectable() export class MyserviceService { constructor() { } } Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class. Before creating a new service, we need to include the service created in the main parent app.module.ts. import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { RouterModule} from ”@angular/router”; import { AppComponent } from ”./app.component”; import { MyserviceService } from ”./myservice.service”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; import { ChangeTextDirective } from ”./change-text.directive”; import { SqrtPipe } from ”./app.sqrt”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, RouterModule.forRoot([ { 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. 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. 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 − 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; } } 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.service”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; todaydate; componentproperty; constructor(private myservice: MyserviceService) {} 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”] }) export class NewCmpComponent implements OnInit { todaydate; newcomponentproperty; newcomponent = “Entered in newcomponent”; constructor(private myservice: MyserviceService) {} ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.newcomponentproperty = this.myservice.serviceproperty; } } In the above component, we are not changing anything but directly assigning the property to the component property. Now when you execute it in the browser, the service property will be changed since the value of it is changed in app.component.ts and the same will be displayed for the new-cmp.component.ts. Also
Angular 4 – Routing
Angular 4 – Routing ”; Previous Next Routing basically means navigating between pages. You have seen many sites with links that direct you to a new page. This can be achieved using routing. Here the pages that we are referring to will be in the form of components. We have already seen how to create a component. Let us now create a component and see how to use routing with it. In the main parent component app.module.ts, we have to now include the router module as shown below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { RouterModule} from ”@angular/router”; import { AppComponent } from ”./app.component”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; import { ChangeTextDirective } from ”./change-text.directive”; import { SqrtPipe } from ”./app.sqrt”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, RouterModule.forRoot([ { path: ”new-cmp”, component: NewCmpComponent } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } import { RouterModule} from ”@angular/router” Here, the RouterModule is imported from angular/router. The module is included in the imports as shown below − RouterModule.forRoot([ { path: ”new-cmp”, component: NewCmpComponent } ]) RouterModule refers to the forRoot which takes an input as an array, which in turn has the object of the path and the component. Path is the name of the router and component is the name of the class, i.e., the component created. Let us now see the component created file − New-cmp.component.ts import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-new-cmp”, templateUrl: ”./new-cmp.component.html”, styleUrls: [”./new-cmp.component.css”] }) export class NewCmpComponent implements OnInit { newcomponent = “Entered in new component created”; constructor() {} ngOnInit() { } } The highlighted class is mentioned in the imports of the main module. New-cmp.component.html <p> {{newcomponent}} </p> <p> new-cmp works! </p> Now, we need the above content from the html file to be displayed whenever required or clicked from the main module. For this, we need to add the router details in the app.component.html. <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, we have created the anchor link tag and given routerLink as “new-cmp”. This is referred in app.module.ts as the path. When a user clicks new component, the page should display the content. For this, we need the following tag – <router-outlet> </router-outlet>. The above tag ensures that the content in the new-cmp.component.html will be displayed on the page when a user clicks new component. Let us now see how the output is displayed on the browser. When a user clicks New component, you will see the following in the browser. The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the original url, which is the path given in the app.module.ts and the router-link in the app.component.html. When a user clicks New component, the page is not refreshed and the contents are shown to the user without any reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user experience as the page is not reloaded. Print Page Previous Next Advertisements ”;
Angular 4 – CLI
Angular 4 – CLI ”; Previous Next Angular CLI makes it easy to start with any Angular project. Angular CLI comes with commands that help us create and start on our project very fast. Let us now go through the commands available to create a project, a component and services, change the port, etc. To work with Angular CLI, we need to have it installed on our system. Let us use the following command for the same − npm install -g @angular/cli To create a new project, we can run the following command in the command line and the project will be created. 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. You can change the port with the following command − ng serve –host 0.0.0.0 –port 4201 The following table lists down a few important commands required while working with Angular 4 projects. 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, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts. Print Page Previous Next Advertisements ”;
Angular 4 – Environment Setup ”; Previous Next In this chapter, we will discuss the Environment Setup required for Angular 4. To install Angular 4, 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. Nodejs To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system. C:>node –v v6.11.0 If it does not print anything, install nodejs on your system. To install nodejs, go the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The homepage of nodejs will look like the following − Based on your OS, install the required package. Once nodejs is installed, npm will also get installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm. C:>npm –v 5.3.0 Angular 4 installations are very simple with the help of angular CLI. Visit the homepage https://cli.angular.io/ of angular to get the reference of the command. Type npm install –g @angular/cli, to install angular cli on your system. You will get the above installation in your terminal, once Angular CLI is installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code, etc. The details of the project setup is explained in the next chapter. Print Page Previous Next Advertisements ”;
Angular 4 – Pipes
Angular 4 – Pipes ”; Previous Next In this chapter, we will discuss what are Pipes in Angular 4. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4. The | character is used to transform data. Following is the syntax for the same {{ Welcome to Angular 4 | lowercase}} It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser. Let us consider a few examples using pipes. Here, we want to display the text given to uppercase. This can be done using pipes as follows − In the app.component.ts file, we have defined the title variable − app.component.ts import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; } The following line of code goes into the app.component.html file. <b>{{title | uppercase}}</b><br/> <b>{{title | lowercase}}</b> The browser appears as shown in the following screenshot − Angular 4 provides some built-in pipes. The pipes are listed below − Lowercasepipe Uppercasepipe Datepipe Currencypipe Jsonpipe Percentpipe Decimalpipe Slicepipe We have already seen the lowercase and uppercase pipes. Let us now see how the other pipes work. The following line of code will help us define the required variables in app.component.ts file − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; todaydate = new Date(); jsonval = {name:”Rox”, age:”25”, address:{a1:”Mumbai”, a2:”Karnataka”}}; months = [“Jan”, “Feb”, “Mar”, “April”, “May”, “Jun”, “July”, “Aug”, “Sept”, “Oct”, “Nov”, “Dec”]; } We will use the pipes in the app.component.html file. <!–The content below is only a placeholder and can be replaced.–> <div style = “width:100%;”> <div style = “width:40%;float:left;border:solid 1px black;”> <h1>Uppercase Pipe</h1> <b>{{title | uppercase}}</b><br/> <h1>Lowercase Pipe</h1> <b>{{title | lowercase}}</b> <h1>Currency Pipe</h1> <b>{{6589.23 | currency:”USD”}}</b><br/> <b>{{6589.23 | currency:”USD”:true}}</b> //Boolean true is used to get the sign of the currency. <h1>Date pipe</h1> <b>{{todaydate | date:”d/M/y”}}</b><br/> <b>{{todaydate | date:”shortTime”}}</b> <h1>Decimal Pipe</h1> <b>{{ 454.78787814 | number: ”3.4-4” }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed. </div> <div style = “width:40%;float:left;border:solid 1px black;”> <h1>Json Pipe</h1> <b>{{ jsonval | json }}</b> <h1>Percent Pipe</h1> <b>{{00.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> The following screenshots show the output for each pipe − How to Create a Custom Pipe? To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows − app.sqrt.ts import {Pipe, PipeTransform} from ”@angular/core”; @Pipe ({ name : ”sqrt” }) export class SqrtPipe implements PipeTransform { transform(val : number) : number { return Math.sqrt(val); } } To create a custom pipe, we have to import Pipe and Pipe Transform from Angular/core. In the @Pipe directive, we have to give the name to our pipe, which will be used in our .html file. Since, we are creating the sqrt pipe, we will name it sqrt. As we proceed further, we have to create the class and the class name is SqrtPipe. This class will implement the PipeTransform. The transform method defined in the class will take argument as the number and will return the number after taking the square root. Since we have created a new file, we need to add the same in app.module.ts. This is done as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; import { ChangeTextDirective } from ”./change-text.directive”; import { SqrtPipe } from ”./app.sqrt”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } We have created the app.sqrt.ts class. We have to import the same in app.module.ts and specify the path of the file. It also has to be included in the declarations as shown above. Let us now see the call made to the sqrt pipe in the app.component.html 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 − Print Page Previous Next Advertisements ”;
Angular 4 – Home
Angular 4 Tutorial PDF Version Quick Guide Resources Job Search Discussion 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). Print Page Previous Next Advertisements ”;
Angular 4 – Event Binding
Angular 4 – Event Binding ”; Previous Next In this chapter, we will discuss how Event Binding works in Angular 4. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouseover, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture. Let us consider an example to understand this better. app.component.html <!–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; 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.component.html file, we have defined a button and added a function to it using the click event. Following is the syntax to define a button and add a function to it. (click)=”myClickFunction($event)” The function is defined in the .ts file: app.component.ts 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. months = [“January”, “Feburary”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; myClickFunction(event) { //just added console.log which will display the event details in browser on click of the button. alert(“Button is clicked”); console.log(event); } } Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot − Let us now add the change event to the dropdown. 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.–> <div style = “text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = “changemonths($event)”> <option *ngFor = “let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf = “isavailable; 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> The function is declared in the app.component.ts file − 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. months = [“January”, “Feburary”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; myClickFunction(event) { alert(“Button is clicked”); console.log(event); } changemonths(event) { console.log(“Changed month from the Dropdown”); console.log(event); } } The console message “Changed month from the Dropdown” is displayed in the console along with the event. Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below − 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. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; myClickFunction(event) { //just added console.log which will display the event details in browser on click of the button. alert(“Button is clicked”); console.log(event); } changemonths(event) { alert(“Changed month from the Dropdown”); } } When the value in dropdown is changed, a dialog box will appear and the following message will be displayed – “Changed month from the Dropdown”. Print Page Previous Next Advertisements ”;