Angular7 – Data Binding

Angular7 – Data Binding ”; Previous Next Data Binding is available right from AngularJS, and all the versions of Angular released later on. 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 7”; // declared array of months. months = [“January”, “February”, “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. 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 as follows − *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. Following is the output of the above month’s array in the browser − The variable that is set in the app.component.ts can be binded inside 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 7”; // declared array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; //variable is set to true } 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”>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 explain 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 7”; // declared array of months. months = [“January”, “Feburary”, “March”, “April”, “May”,”June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = false; //variable is set to true } 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 is given below − <!–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. 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 7”; // declared array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; //variable is set to 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 ”;

Angular7 – CLI Prompts

Angular7 – CLI Prompts ”; 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 Command for Angular Update In case you want to update your application and its dependencies, you can use the following command − ng update @angular/cli @angular/core It will update core framework to the recent version, i.e., Angular 7 and also angular-cli. You can use above command with following options − Angular Important Command List The following table lists down a few important commands required while working with Angular 7 projects − Sr.No Commands and Description 1 Component ng g component new-component 2 Directive ng g directive new-directive 3 Pipe ng g pipe new-pipe 4 Service ng g service new-service 5 Module ng g module my-module 6 Test ng test 7 Build ng build –configuration=production // for production environment ng build –configuration=staging // for stating environment 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 ”;

Testing & Building Angular7 Project

Testing and Building Angular7 Projects ”; Previous Next In this chapter will discuss the following topics − To test Angular 7 Project To build Angular 7 Project Testing Angular 7 Project During the project setup, the required packages for testing are already installed. There is a .spec.ts file created for every new component, service, directive, etc. We are going to use jasmine to write our test cases. For any changes added to your component, services, directives or any other files created, you can include your test cases in the respective .spec.ts files. So most of the unit testing can be covered at the beginning itself. To run the test cases, the command used is as follows− ng test Below is the app.component.spec.ts file for app.component.ts − import { TestBed, async } from ”@angular/core/testing”; import { RouterTestingModule } from ”@angular/router/testing”; import { AppComponent } from ”./app.component”; describe(”AppComponent”, () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); })); it(”should create the app”, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title ”angular7-app”`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual(”angular7-app”); }); it(”should render title in a h1 tag”, () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector(”h1”).textContent).toContain( ”Welcome to angular7-app!”); }) }); app.component.ts import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”angular7-app”; } Now let us run the command to see the test cases running. The test cases status is shown in the command line as shown above and will also open up in the browser as shown below − Incase of any failure, it will show the details as follows − To do that, let us change the app.component.spec.ts as follows − import { TestBed, async } from ”@angular/core/testing”; import { RouterTestingModule } from ”@angular/router/testing”; import { AppComponent } from ”./app.component”; describe(”AppComponent”, () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); })); it(”should create the app”, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have as title ”angular7-app”`, () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual(”Angular 7”); // change the title from angular7-app to Angular 7 }); it(”should render title in a h1 tag”, () => { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector(”h1”).textContent).toContain( ”Welcome to angular7-app!”); }); }); In the above file, the test cases check for the title, Angular 7. But in app.component.ts, we have the title, angular7-app as shown below − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”angular7-app”; } Here the test case will fail and below are the details shown in command line and browser. In command line Following screen is displayed in command line − In browser Following screen is displayed in the browser − All the failed test-cases for your project will be displayed as shown above in command line and browser. Similarly, you can write test cases for your services, directives and the new components which will be added to your project. Building Angular 7 Project Once you are done with the project in Angular, we need to build it so that it can be used in production or stating. The configuration for build, i.e., production, staging, development, testing needs to be defined in your src/environments. At present, we have the following environments defined in src/environment − You can add files based on your build to src/environment, i.e., environment.staging.ts, enviornment.testing.ts, etc. At present, we will try to build for production environment. The file environment.ts contains default environment settings and details of the file as follows − export const environment = { production: false }; To build the file for production, we need to make the production: true in environment.ts as follows − export const environment = { production: true }; The default environment file has to be imported inside components as follows − app.component.ts import { Component } from ”@angular/core”; import { environment } from ”./../environments/environment”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”angular7-app”; } The environment replacement from default to production which we are trying to do are defined inside angular.json fileReplacements section as follows − “production”: { “fileReplacements”: [ { “replace”: “src/environments/environment.ts”, “with”: “src/environments/environment.prod.ts” } ], } When the command for build runs, the file gets replaced to src/environments/environment.prod.ts. The additional configuration like staging or testing can be added here as shown in the below example − “configurations”: { “production”: { … }, “staging”: { “fileReplacements”: [ { “replace”: “src/environments/environment.ts”, “with”: “src/environments/environment.staging.ts” } ] } } So the command to run the build is as follows − ng build –configuration = production // for production environmnet ng build –configuration = staging // for stating enviroment Now let us run the build command for production, the command will create a dist folder inside our project which will have the final files after build. The final files are build inside dist/ folder which can be hosted on the production server at your end. Print Page Previous Next Advertisements ”;

Angular7 – Project Setup

Angular7 – Project Setup ”; Previous Next In this chapter, we shall discuss about the Project Setup in Angular 7. To get started with the project setup, make sure you have nodejs installed. You can check the version of node in the command line using the command, node –v, as shown below − If you do not get the version, install nodejs from their official site −https://nodejs.org/en/. Once you have nodejs installed, npm will also get installed with it. To check npm version, run npm -v in command line as shown below − So we have node version 10 and npm version 6.4.1. To install Angular 7, go to the site, https://cli.angular.io to install Angular CLI. You will see the following commands on the webpage − npm install -g @angular/cli //command to install angular 7 ng new my-dream-app // name of the project cd my-dream-app ng serve The above commands help to get the project setup in Angular 7. We will create a folder called projectA7 and install angular/cli as shown below − Once the installation is done, check the details of the packages installed by using the command ng version as shown below − It gives the version for Angular CLI, typescript version and other packages available for Angular 7. We are done with the installation of Angular 7, now we will start with the project setup. To create a project in Angular 7, we will use the following command − ng new projectname You can use the projectname of your choice. Let us now run the above command in the command line. Here, we use the projectname as angular7-app. Once you run the command it will ask you about routing as shown below − Type y to add routing to your project setup. The next question is about the stylesheet − The options available are CSS, Sass, Less and Stylus. In the above screenshot, the arrow is on CSS. To change, you can use arrow keys to select the one required for your project setup. At present, we shall discuss CSS for our project-setup. The project angular7-app is created successfully. It installs all the required packages necessary for our project to run in Angular7. Let us now switch to the project created, which is in the directory angular7-app. Change the directory in the command line using the given line of code − cd angular7-app We will use Visual Studio Code IDE for working with Angular 7, 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. Following is the Editor − We have not started any project in it. Let us now take the project we have created using angular-cli. We will consider the angular7-app project. Let us open the angular7-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. You will see the below when the command starts executing − 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 url, 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 7!” 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 angular7-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 7.Inside src/ you will app/ folder created during the project setup and holds all the required files required for the project. The angular7-app/ folder has the following file structure − angular.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. package.json − The package.json file tells which libraries will be installed into node_modules when you run npm install. At present, if you open the file package.json in the editor, you will get the following modules added in it − “@angular/animations”: “~7.2.0”, “@angular/common”: “~7.2.0”, “@angular/compiler”: “~7.2.0”, “@angular/core”: “~7.2.0”, “@angular/forms”: “~7.2.0”, “@angular/platform-browser”: “~7.2.0”, “@angular/platform-browser-dynamic”: “~7.2.0”, “@angular/router”: “~7.2.0”, “core-js”: “^2.5.4”, “rxjs”: “~6.3.3”, “tslib”: “^1.9.0”, “zone.js”: “~0.8.26” In case you need to add more libraries, you can add those over here and run the npm install command. tsconfig.json − This basically contains the compiler options required during compilation. tslint.json − This is the config file with rules to be considered while compiling. The src/ folder is the main folder, which internally has a different file structure. app It contains the files described below. These files are installed by angular-cli by default. app.module.ts If you open the file, you will see that the code has reference to different libraries, which are imported. Angular-cli has used these default libraries for the import: angular/core, platform-browser. The names itself explain the usage of the libraries. They are imported and saved into variables such as declarations, imports, providers, and bootstrap. We can see

Angular7 – Pipes

Angular7 – Pipes ”; Previous Next In this chapter, we will discuss about Pipes in Angular 7. Pipes were earlier called filters in Angular1 and called pipes from Angular2 onwards. The | character is used to transform data. Following is the syntax for the same − {{ Welcome to Angular 7 | 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 as follows − 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 7 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 − Here are some built-in pipes available with angular − 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 7 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 as shown below − <!–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 { AppRoutingModule } from ”./app-routing.module”; 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, AppRoutingModule ], 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> Following is the output − Print Page Previous Next Advertisements ”;

Angular7 – Templates

Angular7 – Templates ”; Previous Next Angular 7 uses the <ng-template> as the tag instead of <template>which is used in Angular2. <ng-template> has been in use since the release of Angular 4 , and the earlier version i.e Angular 2 uses <template> for the same purpose. The reason it started to use <ng-template> instead of <template> from Angular 4 onwards is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead. This was one of the major changes made in Angular 4 version. Let us now use the template along with the if else condition and see the output. 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 (change) = “changemonths($event)” name = “month”> <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 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, we have added the if statement with the else condition and will call template condition1, else condition2. 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, then the condition1 template is called, otherwise condition2. 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 7”; // declared array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = false; // variable is set to 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”); } } The output in the browser is as follows − The variable isavailable is false so the condition2 template is printed. If you click the button, the respective template will be called. 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 7”; // declared array of months. months = [“January”, “Feburary”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = false; //variable is set to true myClickFunction(event) { this.isavailable = !this.isavailable; // variable is toggled onclick of the button } changemonths(event) { alert(“Changed month from the Dropdown”); } } The isavailable variable is toggled on click of the button as shown below − myClickFunction(event) { this.isavailable = !this.isavailable; } When you click on the button based on the value of the isavailable variable the respective template will be displayed − If you inspect the browser, you will see that you never get the span tag in the dom. The following example will help you understand the same. Though in app.component.html we have added span tag and the <ng-template> for the condition as shown below − <span *ngIf = “isavailable;then condition1 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> We do not see the span tag and also the <ng-template> in the dom structure when we inspect the same in browser. The following line of code in html will help us get the span tag in the dom − <!–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)” name = “month”> <option *ngFor = “let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf = “isavailable; 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, we get the “Condition is valid” message in the browser and the span tag is also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true. Print Page Previous Next Advertisements ”;

Angular7 – Components

Angular7 – Components ”; Previous Next Major part of the development with Angular 7 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 And if you have selected angular routing during your project setup, files related to routing will also get added and the files are as follows − app-routing.module.ts The above files are 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 { AppRoutingModule } from ”./app-routing.module”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], 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 with the below line of code − ng g component new-cmp When you run the above command in the command line, you will receive the following output − C:projectA7angular7-app>ng g 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 (477 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 { AppRoutingModule } from ”./app-routing.module”; 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, AppRoutingModule ], 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”, // selector to be used inside .html file. 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 there is 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 − <html lang = “en”> <head> <meta charset = “utf-8”> <title>Angular7App</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. We shall 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).catch(err => console.error(err)); 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 { AppRoutingModule } from ”./app-routing.module”; import { AppComponent } from ”./app.component”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; @NgModule({ declarations: [ AppComponent, NewCmpComponent ], imports: [ BrowserModule, AppRoutingModule ” ], 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 7”; } 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

Angular7 – Modules

Angular7 – 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 { AppRoutingModule } from ”./app-routing.module”; import { AppComponent } from ”./app.component”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; @NgModule({ declarations: [ AppComponent, NewCmpComponent ], imports: [ BrowserModule, AppRoutingModule ], 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, NewCmpComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations, imports, 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 with the below code − 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 ”;

Angular7 – Event Binding

Angular7 – Event Binding ”; Previous Next In this chapter, we will discuss how Event Binding works in Angular 7. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouse over, 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 :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 7”; // declared array of months. months = [“January”, “February”, “March”, “April”, “May”,”June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; //variable is set to 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 − The styling for button is added in add.component.css − button { background-color: #2B3BCF; border: none; color: white; padding: 10px 10px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; } Let us now add the onchange event to the dropdown. The following line of code will help you add the change event to the dropdown − 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 (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> <br/> <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 7”; // declared array of months. months = [“January”, “Feburary”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; //variable is set to 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) { console.log(“Changed month from the Dropdown”); console.log(event); } } Select month from the dropdown and you see 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 7”; // declared array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; //variable is set to 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 ”;

Angular7 – Home

Angular7 Tutorial PDF Version Quick Guide Resources Job Search Discussion Angular 7 is an open source 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 have 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. Why to Learn Angular 7? Angular 7 is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Software Development Domain. I will list down some of the key advantages of learning Angular 7: Angular is the most stable and most popular javascript based platform now-a-days. Angular development is a complete suite for an application development and you can have following roles after learning Angular in a company. Web developer Web app developer UI developer UX developer Front-end developer JavaScript developer Applications of Angular 7 As mentioned before, Angular 7 is one of the most widely used language over the web. I”m going to list few of them here: Google Supported Community – Google actively supports Angular and its development. Angular is used in various Google Apps. POJO based development – Angular heavily used Plain Old JavaScript Object and it helps in learning Angular in an easier way. Declarative User Interface – Angular uses HTML as view language and extends its functionality. It helps in handling UI vs code differentiation and UI is loosely coupled with code. Typescript – Typescript is super set of javascript and is easy to debug. It is highly secure and is object oriented. Modular Structure – Angular development is highly modular, is component based and is highly maintainable. Multi-platform support – Angular code works well on all platforms without much change in code. Audience This tutorial is designed for software programmers who want to learn the basics of Angular 7 and its programming concepts in a simple and easy manner. This tutorial will give you enough understanding on the various functionalities of Angular 7 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 ”;