Angular 6 – Environment Setup

Angular 6 – Environment Setup ”; Previous Next In this chapter, we will discuss the Environment Setup required for Angular 6. To install Angular 6, we require the following − Nodejs Npm Angular CLI IDE for writing your code Nodejs has to be greater than 8.11 and npm has to be greater than 5.6. 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 v8.11.3 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.6.0 Angular 6 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 6 – Event Binding

Angular 6 – Event Binding ”; Previous Next In this chapter, we will discuss how Event Binding works in Angular 6. 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 6 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 6 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 6 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 ”;

Angular 6 – Forms

Angular 6 – Forms ”; Previous Next In this chapter, we will see how forms are used in Angular 6. We will discuss two ways of working with forms – template driven form and model driven forms. Template Driven Form With a template driven form, most of the work is done in the template; and with the model driven form, most of the work is done in the component class. Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit the button in the form. To start with, we need to import to FormsModule from @angular/core which is done in app.module.ts as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { RouterModule} from ”@angular/router”; import { HttpModule } from ”@angular/http”; import { FormsModule } from ”@angular/forms”; 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, HttpModule, FormsModule, RouterModule.forRoot([ {path: ”new-cmp”,component: NewCmpComponent} ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code. Let us now create our form in the app.component.html file. <form #userlogin = “ngForm” (ngSubmit) = “onClickSubmit(userlogin.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, password and the submit button. We have assigned type, name, and placeholder to it. In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it. If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it. Let us now create the function in the app.component.ts and fetch the values entered in the form. 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 6 Project!”; todaydate; componentproperty; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } onClickSubmit(data) { alert(“Entered Email id : ” + data.emailid); } } In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function. This is how the browser is displayed − The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already entered. The email id is displayed at the bottom as shown in the above screenshot. Model Driven Form In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array. There is a change which goes in app.module.ts. import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { RouterModule} from ”@angular/router”; import { HttpModule } from ”@angular/http”; import { ReactiveFormsModule } from ”@angular/forms”; 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, HttpModule, ReactiveFormsModule, RouterModule.forRoot([ { path: ”new-cmp”, component: NewCmpComponent } ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from ”@angular/forms”. import { Component } from ”@angular/core”; import { MyserviceService } from ”./myservice.service”; import { FormGroup, FormControl } from ”@angular/forms”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 6 Project!”; todaydate; componentproperty; emailid; formdata; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.formdata = new FormGroup({ emailid: new FormControl(“[email protected]”), passwd: new FormControl(“abcd1234”) }); } onClickSubmit(data) {this.emailid = data.emailid;} } The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to. This is how the values will be seen in the form UI. We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html. <div> <form [formGroup] = “formdata” (ngSubmit) = “onClickSubmit(formdata.value)” > <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}} </p> In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]=”formdata”. On submit, the function is called onClickSubmit for which formdata.value is passed. The input tag formControlName is used. It is given a value that we have used in the app.component.ts file. On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file. On clicking Login, the value will be displayed as shown in the above screenshot. Form Validation Let us now discuss form validation using model driven form. You can use the built-in form validation

Angular 6 – Home

Angular 6 Tutorial Quick Guide Resources Job Search Discussion Angular 6 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 6 and its programming concepts in a simple and easy manner. This tutorial will give you enough understanding on the various functionalities of Angular 6 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 6 – Data Binding

Angular 6 – Data Binding ”; Previous Next Data Binding is available right from AngularJS, Angular 2,4 and is now available in Angular 6 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 6 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 : <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. 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 Let us try the above example using the IF THEN ELSE condition. 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. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = false; } In this case, we have made the isavailable variable as false. To print the else condition, we will have to create the ng-template as follows − <ng-template #condition1>Condition is invalid</ng-template> The full code looks like this − <!–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; else condition1″>Condition is valid.</span> <ng-template #condition1>Condition is invalid</ng-template> </div> If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-template, and when the available variable is set to false the text Condition is invalid is displayed. The following screenshot shows the display in the browser. Let us now use the if then else condition. 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; } Now, we will make the variable isavailable as true. In the html, 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}}. </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> If the variable is true, then condition1, else condition2. Now, two templates are created with id #condition1 and #condition2. The display in the browser is as follows − Print Page Previous Next Advertisements ”;

Angular 6 – Http Client

Angular 6 – Http Client ”; Previous Next HttpClient is introduced in Angular 6 and it will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service. To start using the http service, we need to import the module in app.module.ts as shown below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { HttpClientModule } from ”@angular/common/http”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } If you see the highlighted code, we have imported the HttpClientModule from @angular/common/http and the same is also added in the imports array. Let us now use the http client in the app.component.ts. import { Component } from ”@angular/core”; import { HttpClient } from ”@angular/common/http”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { constructor(private http: HttpClient) { } ngOnInit() { this.http.get(“http://jsonplaceholder.typicode.com/users”). subscribe((data) ⇒ console.log(data)) } } Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows − import { HttpClient } from ”@angular/common/http”; In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows this.http.get(); It takes the url to be fetched as the parameter as shown in the code. We will use the test url − https://jsonplaceholder.typicode.com/users to fetch the json data. The subscribe will log the output in the console as shown in the browser − If you see, the json objects are displayed in the console. The objects can be displayed in the browser too. For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows − import { Component } from ”@angular/core”; import { HttpClient } from ”@angular/common/http”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { constructor(private http: HttpClient) { } httpdata; ngOnInit() { this.http.get(“http://jsonplaceholder.typicode.com/users”) .subscribe((data) => this.displaydata(data)); } displaydata(data) {this.httpdata = data;} } In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it. In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file. <ul *ngFor = “let data of httpdata”> <li>Name : {{data.name}} Address: {{data.address.city}}</li> </ul> The json object is as follows − { “id”: 1, “name”: “Leanne Graham”, “username”: “Bret”, “email”: “[email protected]”, “address”: { “street”: “Kulas Light”, “suite”: “Apt. 556”, “city”: “Gwenborough”, “zipcode”: “92998-3874”, “geo”: { “lat”: “-37.3159”, “lng”: “81.1496” } }, “phone”: “1-770-736-8031 x56442”, “website”: “hildegard.org”, “company”: { “name”: “Romaguera-Crona”, “catchPhrase”: “Multi-layered client-server neural-net”, “bs”: “harness real-time e-markets” } } The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file. This is how the display is shown in the browser − Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed. Following are the changes done in app.component.html and app.component.ts files − app.component.ts import { Component } from ”@angular/core”; import { HttpClient } from ”@angular/common/http”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { constructor(private http: HttpClient) { } httpdata; name; searchparam = 2; ngOnInit() { this.http.get(“http://jsonplaceholder.typicode.com/users?id=”+this.searchparam) .subscribe((data) => this.displaydata(data)); } displaydata(data) {this.httpdata = data;} } For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id = 2 from the json file. This is how the browser is displayed − We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id = 2 is displayed in the browser. Print Page Previous Next Advertisements ”;

Angular 6 – Components

Angular 6 – Components ”; Previous Next Major part of the development with Angular 6 is done in the components. Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure in one of our previous chapters. The file structure has the app component and it consists of the following files − app.component.css app.component.html app.component.spec.ts app.component.ts app.module.ts The above files were created by default when we created new project using the angular-cli command. If you open up the app.module.ts file, it has some libraries which are imported and also a declarative which is assigned the appcomponent as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The declarations include the AppComponent variable, which we have already imported. This becomes the parent component. Now, angular-cli has a command to create your own component. However, the app component which is created by default will always remain the parent and the next components created will form the child components. Let us now run the command to create the component. ng generate component new-cmp When you run the above command in the command line, you will receive the following output − D:NodeAngular6App>ng generate component new-cmp CREATE src/app/new-cmp/new-cmp.component.html (26 bytes) CREATE src/app/new-cmp/new-cmp.component.spec.ts (629 bytes) CREATE src/app/new-cmp/new-cmp.component.ts (272 bytes) CREATE src/app/new-cmp/new-cmp.component.css (0 bytes) UPDATE src/app/app.module.ts (398 bytes) Now, if we go and check the file structure, we will get the new-cmp new folder created under the src/app folder. The following files are created in the new-cmp folder − new-cmp.component.css − css file for the new component is created. new-cmp.component.html − html file is created. new-cmp.component.spec.ts − this can be used for unit testing. new-cmp.component.ts − here, we can define the module, properties, etc. Changes are added to the app.module.ts file 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”; // includes the new-cmp component we created @NgModule({ declarations: [ AppComponent, NewCmpComponent // here it is added in declarations and will behave as a child component ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] //for bootstrap the AppComponent the main app component is given. }) export class AppModule { } The new-cmp.component.ts file is generated as follows − import { Component, OnInit } from ”@angular/core”; // here angular/core is imported . @Component({ // this is a declarator which starts with @ sign. The component word marked in bold needs to be the same. selector: ”app-new-cmp”, // templateUrl: ”./new-cmp.component.html”, // reference to the html file created in the new component. styleUrls: [”./new-cmp.component.css”] // reference to the style file. }) export class NewCmpComponent implements OnInit { constructor() { } ngOnInit() {} } If you see the above new-cmp.component.ts file, it creates a new class called NewCmpComponent, which implements OnInit.In, which has a constructor and a method called ngOnInit(). ngOnInit is called by default when the class is executed. Let us check how the flow works. Now, the app component, which is created by default becomes the parent component. Any component added later becomes the child component. When we hit the url in the http://localhost:4200/ browser, it first executes the index.html file which is shown below − <!doctype html> <html lang = “en”> <head> <meta charset = “utf-8”> <title>Angular 6 Application</title> <base href = “/”> <meta name = “viewport” content = “width = device-width, initial-scale = 1”> <link rel = “icon” type = “image/x-icon” href = “favicon.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. 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. This tag has the reference in the main.ts file. import { enableProdMode } from ”@angular/core”; import { platformBrowserDynamic } from ”@angular/platform-browser-dynamic”; import { AppModule } from ”./app/app.module”; import { environment } from ”./environments/environment”; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule); AppModule is imported from the app of the main parent module, and the same is given to the bootstrap Module, which makes the appmodule load. Let us now see the app.module.ts file − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; @NgModule({ declarations: [ AppComponent, NewCmpComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, the AppComponent is the name given, i.e., the variable to store the reference of the app. Component.ts and the same is given to the bootstrap. Let us now see 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 6 Project!”; } Angular core is imported and referred as the Component and the same is used in the Declarator as − @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) In the declarator reference to the selector, templateUrl and styleUrl are given. The selector here is nothing but the tag which is placed in the index.html file that we saw above. The class AppComponent has a variable called title, which is displayed in the browser. The @Component uses the templateUrl called app.component.html which is as follows − <!–The content below is only a placeholder and can be replaced.–> <div style = “text-align:center”> <h1> Welcome to {{title}}. </h1> </div> It has just the html code and the variable title in curly brackets. It gets replaced with the value, which is present in the app.component.ts file. This is called binding. We will discuss the concept of binding in a subsequent chapter. Now that we have created a new component called new-cmp. The same gets included in the app.module.ts file, when the command

Angular 6 – Project Setup

Angular 6 – Project Setup ”; Previous Next AngularJS is based on the model view controller, whereas Angular 4 is based on the components structure. Angular 6 works on the same structure as Angular4 but is faster when compared to Angular4. Angular6 uses TypeScript 2.9 version whereas Angular 4 uses TypeScript version 2.2. This brings a lot of difference in the performance. To install Angular 6, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 6. 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 v8.11.3 is recommended for users. Users who already have nodejs greater than 8.11 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 − node -v v8.11.3 The command prompt shows v8.11.3. 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. npm -v v5.6.0 The version of npm is 5.6.0. Now that we have nodejs and npm installed, let us run the angular cli commands to install Angular 6. You will see the following commands on the webpage − npm install -g @angular/cli //command to install angular 6 ng new Angular 6-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. npm install -g @angular/cli //command to install angular 6 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 _ _ ____ _ ___ / _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / ? | ”_ / _` | | | | |/ _` | ”__| | | | | | | / ___ | | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ __| |_|__, |__,_|_|__,_|_| ____|_____|___| |___/ Angular CLI: 6.1.3 Node: 8.11.3 OS: win32 x64 Angular: … Package Version —————————————————— @angular-devkit/architect 0.7.3 @angular-devkit/core 0.7.3 @angular-devkit/schematics 0.7.3 @schematics/angular 0.7.3 @schematics/update 0.7.3 rxjs 6.2.2 typescript 2.9.2 We get the @angular/cli version, which is at present 6.1.3. The node version running is 8.11.3 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 6. Let us now create our first project in Angular 6. To create a project in Angular 6, we will use the following command − ng new projectname We will name the project ng new Angular6App. Let us now run the above command in the command line. ng new Angular6App CREATE Angular6App/angular.json (3593 bytes) CREATE Angular6App/package.json (1317 bytes) CREATE Angular6App/README.md (1028 bytes) CREATE Angular6App/tsconfig.json (408 bytes) CREATE Angular6App/tslint.json (2805 bytes) CREATE Angular6App/.editorconfig (245 bytes) CREATE Angular6App/.gitignore (503 bytes) CREATE Angular6App/src/favicon.ico (5430 bytes) CREATE Angular6App/src/index.html (298 bytes) CREATE Angular6App/src/main.ts (370 bytes) CREATE Angular6App/src/polyfills.ts (3194 bytes) CREATE Angular6App/src/test.ts (642 bytes) CREATE Angular6App/src/styles.css (80 bytes) CREATE Angular6App/src/browserslist (375 bytes) CREATE Angular6App/src/karma.conf.js (964 bytes) CREATE Angular6App/src/tsconfig.app.json (170 bytes) CREATE Angular6App/src/tsconfig.spec.json (256 bytes) CREATE Angular6App/src/tslint.json (314 bytes) CREATE Angular6App/src/assets/.gitkeep (0 bytes) CREATE Angular6App/src/environments/environment.prod.ts (51 bytes) CREATE Angular6App/src/environments/environment.ts (642 bytes) CREATE Angular6App/src/app/app.module.ts (314 bytes) CREATE Angular6App/src/app/app.component.html (1141 bytes) CREATE Angular6App/src/app/app.component.spec.ts (1010 bytes) CREATE Angular6App/src/app/app.component.ts (215 bytes) CREATE Angular6App/src/app/app.component.css (0 bytes) CREATE Angular6App/e2e/protractor.conf.js (752 bytes) CREATE Angular6App/e2e/tsconfig.e2e.json (213 bytes) CREATE Angular6App/e2e/src/app.e2e-spec.ts (307 bytes) CREATE Angular6App/e2e/src/app.po.ts (208 bytes) The project Angular6App is created successfully. It installs all the required packages necessary for our project to run in Angular 6. Let us now switch to the project created, which is in the directory Angular6App. Change the directory in the command line – cd Angular 6-app. We will use Visual Studio Code IDE for working with Angular 6; 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. 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. ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** … Date: 2018-08-18T11:17:54.745Z Hash: 0ace6c8a055c58d1734c Time: 20490ms chunk {main} main.js, main.js.map (main) 10.7 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 227 kB [initial] [rendered] chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered] chunk {styles} styles.js, styles.js.map (styles) 15.6 kB [initial] [rendered] chunk {vendor} vendor.js, vendor.js.map (vendor) 3.27 MB [initial] [rendered] i ?wdm?: Compiled successfully. The web server starts on port 4200. Type the url http://localhost:4200/ in the browser and see the output. You will be directed to the following screen − Let us now make some changes to display the following content − “Welcome to Angular

Angular 6 – Directives

Angular 6 – Directives ”; Previous Next Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below − Component Directives These form the main class having details of how the component should be processed, instantiated and used at runtime. Structural Directives A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor. Attribute Directives Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below. How to Create Custom Directives? In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard. Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is − ng g directive nameofthedirective e.g ng g directive changeText This is how it appears in the command line C:projectA6Angular6App>ng g directive changeText CREATE src/app/change-text.directive.spec.ts (241 bytes) CREATE src/app/change-text.directive.ts (149 bytes) UPDATE src/app/app.module.ts (486 bytes) The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated. app.module.ts 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”; @NgModule({ declarations: [ AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below. change-text. directive import { Directive } from ”@angular/core”; @Directive({ selector: ”[appChangeText]” }) export class ChangeTextDirective { constructor() { } } The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive. In the app.component.html view, let us add the directive as follows − <div style = “text-align:center”> <span appChangeText >Welcome to {{title}}.</span> </div> We will write the changes in change-text.directive.ts file as follows − change-text.directive.ts import { Directive, ElementRef} from ”@angular/core”; @Directive({ selector: ”[appChangeText]” }) export class ChangeTextDirective { constructor(Element: ElementRef) { console.log(Element); Element.nativeElement.innerText = “Text is changed by changeText Directive. “; } } In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied. We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above. Now, the browser will show the following. Print Page Previous Next Advertisements ”;

Angular 6 – Module

Angular 6 – Modules ”; Previous Next Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application. In case you are developing a website, the header, footer, left, center and the right section become part of a module. To define module, we can use the NgModule. When you create a new project using the Angular -cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The NgModule needs to be imported as follows − import { NgModule } from ”@angular/core”; The structure for the ngmodule is as shown below − @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap. Declaration It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below − declarations: [ AppComponent, NewCmpComponent ] Import It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your application needs forms, you can include the module as follows − import { FormsModule } from ”@angular/forms”; The import in the @NgModule will be like the following − imports: [ BrowserModule, FormsModule ] Providers This will include the services created. Bootstrap This includes the main app component for starting the execution. Print Page Previous Next Advertisements ”;