Angular7 – Useful Resources

Angular7 – Useful Resources ”; Previous Next The following resources contain additional information on Angular7. Please use them to get more in-depth knowledge on this. Useful Video Courses Angular – The Complete Course 14 Lectures 48 mins Ganesh Kavhar More Detail Angular JS Full Stack: Create and Host Listing/Classified Site 59 Lectures 4 hours Jay R More Detail Full-Stack web app development with Angular 12, .NET Core Web API & Mongo DB Most Popular 20 Lectures 49 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & Microsoft SQL Full Stack Web Development 21 Lectures 55 mins Vinay Kumar More Detail Angular 12, .NET Core Web API and MySQL Web Development 21 Lectures 51 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & PostgreSQL Full Stack Web Development 5 Lectures 51 mins Vinay Kumar More Detail Print Page Previous Next Advertisements ”;

Angular7 – Quick Guide

Angular7 – Quick Guide ”; Previous Next Angular7 – Overview Angular 7 is owned by Google and the stable release was done on 18th October 2018. This is the latest version of Angular. Below is the list of Angular versions released so far − Version Released Date Angular JS October 2010 Angular 2.0 Sept 2016 Angular 4.0 March 2017 Angular 5.0 November 2017 Angular 6.0 May 2018 Angular 7.0 October 2018 The release dates for the next two major upcoming versions of Angular are given below − Version Released Date Angular 8.0 March/April 2019 Angular 9.0 September/ October 2019 Google plans to release the major Angular version every 6 months. The version released so far are backward compatible and can be updated to the newer one very easily. Let us discuss the new features added to Angular 7. Angular Update to V7 Angular 7 is a major release where in the angular core framework, Angular CLI, Angular Materials are updated. In case you are using Angular 5 or 6 and want to update to Angular 7, below is the command which will update your app to the recent version of Angular − ng update @angular/cli @angular/core Angular CLI While doing project setup using angular CLI, it prompts you about the built-in features available, i.e., routing and stylesheet support as shown below − Application Performance In Angular 7, there is bundle budget added in angular.json as shown below − Budgets is a feature added to Angular CLI which allows you to set limit inside your configuration to make sure your application size is within the limit set. You can set the size so that the app can be warned when the limit is crossed. Angular Material and CDK The version of Angular Material/CDK is updated in Angular 7. Also there are 2 features added to CDK − virtual scrolling, and drag and drop. Virtual Scrolling Virtual scrolling feature shows up the visible dom elements to the user, as the user scrolls, the next list is displayed. This gives faster experience as the full list is not loaded at one go and only loaded as per the visibility on the screen. Drag and Drop You can drag and drop elements from a list and place it wherever required within the list. The new feature is very smooth and fast. Angular7 – Environment Setup In this chapter, we will discuss the Environment Setup required for Angular 7. To install Angular 7, we require the following − Nodejs Npm Angular CLI IDE for writing your code 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. Nodejs has to be greater than 8.x or 10.x, and npm has to be greater than 5.6 or 6.4. C:>node –v v10.15.1 If it does not print anything, install nodejs on your system. To install nodejs, go to the homepage, https://nodejs.org/en/download/of nodejs and install the package based on your OS. The homepage of nodejs is as follows − 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 as given below. It will display the version of the npm. C:>npm –v 6.4.1 Angular 7 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 in your command prompt, to install angular cli on your system. It will take a while to install and once done you can check the version using below command − ng version It will display version details of angular – cli as well version of others packages as shown below − We are done with the installation of Angular 7. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual Studio Code to start working with Angular 7. The details of the project setup are explained in the next chapter. Angular7 – Project Setup 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

Angular7 – Materials

Angular7 – Materials ”; Previous Next Materials offer a lot of built-in modules for your project. Features such as autocomplete, datepicker, slider, menus, grids, and toolbar are available for use with materials in Angular 7. To use materials, we need to import the package. Angular 2 also has all the above features but they are available as part of the @angular/core module. From Angular 4, Materials module has been made available with a separate module @angular/materials. This helps the user to import only the required materials in their project. To start using materials, you need to install two packages: materials and cdk. Material components depend on the animation module for advanced features. Hence you need the animation package for the same, @angular/animations. The package has already been updated in the previous chapter. We have already installed @angular/cdk packages in previous chapters for virtual and drag drop module. Following is the command to add materials to your project − npm install –save @angular/material Let us now see the package.json. @angular/material and @angular/cdk are installed. { “name”: “angular7-app”, “version”: “0.0.0”, “scripts”: { “ng”: “ng”, “start”: “ng serve”, “build”: “ng build”, “test”: “ng test”, “lint”: “ng lint”, “e2e”: “ng e2e” }, “private”: true, “dependencies”: { “@angular/animations”: “~7.2.0”, “@angular/cdk”: “^7.3.4”, “@angular/common”: “~7.2.0”, “@angular/compiler”: “~7.2.0”, “@angular/core”: “~7.2.0”, “@angular/forms”: “~7.2.0”, “@angular/material”: “^7.3.4”, “@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” }, “devDependencies”: { “@angular-devkit/build-angular”: “~0.13.0”, “@angular/cli”: “~7.3.2”, “@angular/compiler-cli”: “~7.2.0”, “@angular/language-service”: “~7.2.0”, “@types/node”: “~8.9.4”, “@types/jasmine”: “~2.8.8”, “@types/jasminewd2”: “~2.0.3”, “codelyzer”: “~4.5.0”, “jasmine-core”: “~2.99.1”, “jasmine-spec-reporter”: “~4.2.1”, “karma”: “~3.1.1”, “karma-chrome-launcher”: “~2.2.0”, “karma-coverage-istanbul-reporter”: “~2.0.1”, “karma-jasmine”: “~1.1.2”, “karma-jasmine-html-reporter”: “^0.2.2”, “protractor”: “~5.4.0”, “ts-node”: “~7.0.0”, “tslint”: “~5.11.0”, “typescript”: “~3.2.2″ } } We have highlighted the packages that are installed to work with materials. We will now import the modules in the parent module – app.module.ts as shown below. import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; import { ScrollDispatchModule } from ”@angular/cdk/scrolling”; import { DragDropModule } from ”@angular/cdk/drag-drop”; import { ReactiveFormsModule } from ”@angular/forms”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { MatButtonModule, MatMenuModule, MatSidenavModule } from ”@angular/material”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule, ReactiveFormsModule, BrowserAnimationsModule, MatButtonModule, MatMenuModule, MatSidenavModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } In the above file, we have imported the following modules from @angular/materials. import { MatButtonModule, MatMenuModule, MatSidenavModule } from ”@angular/material”; And the same is used in the imports array as shown below − imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule, ReactiveFormsModule, BrowserAnimationsModule, MatButtonModule, MatMenuModule, MatSidenavModule ], The app.component.ts is as shown below − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { constructor() {} } Let us now add the material-css support in styles.css. @import “~@angular/material/prebuilt-themes/indigo-pink.css”; Let us now add materials inside app.component.html Menu To add menu, <mat-menu></mat-menu> is used. The file and Save As items are added to the button under mat-menu. There is a main button added Menu. The reference of the same is given the <mat-menu> by using [matMenuTriggerFor]=”menu” and using the menu with # in<mat-menu>. app.component.html <button mat-button [matMenuTriggerFor] = “menu”>Menu</button> <mat-menu #menu = “matMenu”> <button mat-menu-item> File </button> <button mat-menu-item> Save As </button> </mat-menu> The below image is displayed in the browser − Clicking on Menu will display the items inside it − SideNav To add sidenav, we need <mat-sidenav-container></mat-sidenav-container>. <mat-sidenav></mat-sidenav> is added as a child to the container. There is another div added, which triggers the sidenav by using (click)=”sidenav.open()”. app.component.html <mat-sidenav-container class=”example-container” fullscreen> <mat-sidenav #sidenav class = “example-sidenav”> Angular 7 </mat-sidenav> <div class = “example-sidenav-content”> <button type = “button” mat-button (click) = “sidenav.open()”> Open sidenav </button> </div> </mat-sidenav-container> app.component.css .example-container { width: 500px; height: 300px; border: 1px solid rgba(0, 0, 0, 0.5); } .example-sidenav { padding: 20px; width: 150px; font-size: 20px; border: 1px solid rgba(0, 0, 0, 0.5); background-color: #ccc; color:white; } Following is the display of menu and sidenav in the browser − Following panel opens up on the left side if we click on Open Sidenav − Datepicker Let us now add a datepicker using materials. To add a datepicker, we need to import the modules required to show the datepicker. In app.module.ts, we have imported the following module as shown below for datepicker − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; import { ScrollDispatchModule } from ”@angular/cdk/scrolling”; import { DragDropModule } from ”@angular/cdk/drag-drop”; import { ReactiveFormsModule } from ”@angular/forms”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { MatDatepickerModule, MatInputModule, MatNativeDateModule } from ”@angular/material”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule, ReactiveFormsModule, BrowserAnimationsModule, MatDatepickerModule, MatInputModule, MatNativeDateModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } Here, we have imported modules such as MatDatepickerModule, MatInputModule, and MatNativeDateModule. Now, the app.component.ts is as shown below − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, s tyleUrls: [”./app.component.css”] }) export class AppComponent { constructor() {} } The app.component.html is as shown below − <mat-form-field> <input matInput [matDatepicker] = “picker” placeholder = “Choose a date”> <mat-datepicker-toggle matSuffix [for] = “picker”></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> Global css added in style.css − /* You can add global styles to this file, and also import other style files */ @import ”~@angular/material/prebuilt-themes/deeppurple-amber.css”; body { font-family: Roboto, Arial, sans-serif; margin: 10; } .basic-container { padding: 30px; } .version-info { font-size: 8pt; float: right; } The datepicker is displayed in the browser as shown below −

Angular7 – Http Client

Angular7 – Http Client ”; Previous Next HttpClient 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 { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [MyserviceService], 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. We will fetch the data from the server using httpclient module declared above. We will do that inside a service we created in the previous chapter and use the data inside the components which we want. myservice.service.ts import { Injectable } from ”@angular/core”; import { HttpClient } from ”@angular/common/http”; @Injectable({ providedIn: ”root” }) export class MyserviceService { private finaldata = []; private apiurl = “http://jsonplaceholder.typicode.com/users”; constructor(private http: HttpClient) { } getData() { return this.http.get(this.apiurl); } } There is a method added called getData that returns the data fetched for the url given. The method getData is called from app.component.ts 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 7 Project!”; public persondata = []; constructor(private myservice: MyserviceService) {} ngOnInit() { this.myservice.getData().subscribe((data) => { this.persondata = Array.from(Object.keys(data), k=>data[k]); console.log(this.persondata); }); } } We are calling the method getData which gives back an observable type data. The subscribe method is used on it which has an arrow function with the data we need. When we check in the browser, the console displays the data as shown below − Let us use the data in app.component.html as follows − <h3>Users Data</h3> <ul> <li *ngFor=”let item of persondata; let i = index”< {{item.name}} </li> </ul> Output Print Page Previous Next Advertisements ”;

Angular7 – Discussion

Discuss Angular7 ”; Previous Next 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. Print Page Previous Next Advertisements ”;

Angular7 – Materials/CDK-Drag & Drop

Angular7 – Materials/CDK-Drag and Drop ”; Previous Next The new Drag and Drop feature added to Angular 7 CDK helps to drag and drop the elements from the list. We will understand the working of Drag and Drop Module with the help of an example. The feature is added to cdk. We need to first download the dependency as shown below − npm install @angular/cdk –save Once the above step is done. Let us import the drag and drop module in app.module.ts as shown below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; import { ScrollDispatchModule } from ”@angular/cdk/scrolling”; import { DragDropModule } from ”@angular/cdk/drag-drop”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } The DragDropModule is imported from ”@angular/cdk/drag-drop” and the module is added to import array as shown above. We will use details from the api, (http://jsonplaceholder.typicode.com/users) to be displayed on the screen. We have service which will fetch the data from the api as shown below − myservice.service.ts import { Injectable } from ”@angular/core”; import { HttpClient } from ”@angular/common/http”; @Injectable({ providedIn: ”root” }) export class MyserviceService { private finaldata = []; private apiurl = “http://jsonplaceholder.typicode.com/users”; constructor(private http: HttpClient) { } getData() { return this.http.get(this.apiurl); } } Once done call the service inside app.component.ts as shown below − 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 7 Project!”; public personaldetails = []; constructor(private myservice: MyserviceService) {} ngOnInit() { this.myservice.getData().subscribe((data) => { this.personaldetails = Array.from(Object.keys(data), k=>data[k]); console.log(this.personaldetails); }); } } We have the required data available in personaldetails variable. Now let us use the same to display to the user as shown below − <h3>Angular 7 – Drag and Drop Module</h3> <div> <div *ngFor=”let item of personaldetails; let i = index” class=”divlayout”> {{item.name}} </div > </div> We have added class = ”divlayout” and the details of the class are in app.component.css. .divlayout{ width: 40%; background-color: #ccc; margin-bottom: 5px; padding: 10px 10px; border: 3px solid #73AD21; } Following screen will be displayed in the browser − It will not drag and drop anything, we need to add the dragdrop cdk properties in app.component.html as shown below − <h3>Angular 7 – Drag and Drop Module</h3> <div cdkDropList #personList = “cdkDropList” [cdkDropListData] = “personaldetails” [cdkDropListConnectedTo] = “[userlist]” class = “example-list” (cdkDropListDropped) = “onDrop($event)” > <div *ngFor = “let item of personaldetails; let i = index” class = “divlayout” cdkDrag> {{item.name}} </div > </div&t; The highlighted ones are all the properties required to perform drag and drop. When you check in the browser, it allows you to drag the item. It will not drop it in the list and will remain as it is when you leave the mouse pointer. Here it allows to drag the item from the list but once you leave the mouse pointer it will go and settle in the same place. To add the drop feature, we need to add the event onDrop in app.component.ts as shown below − First we have to import the dragdrap cdk modules as shown below − import {CdkDragDrop, moveItemInArray, transferArrayItem} from ”@angular/cdk/drag-drop”; Here is the full code in app.component.ts − import { Component } from ”@angular/core”; import { MyserviceService } from ”./myservice.service”; import {CdkDragDrop, moveItemInArray, transferArrayItem} from ”@angular/cdk/drag-drop”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 7 Project!”; public personaldetails = []; constructor(private myservice: MyserviceService) {} ngOnInit() { this.myservice.getData().subscribe((data) => { this.personaldetails = Array.from(Object.keys(data), k=>data[k]); console.log(this.personaldetails); }); } onDrop(event: CdkDragDrop<string[]>) { if (event.previousContainer === event.container) { moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); } else { transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex); } } } The function onDrop takes care of dropping the item dragged in the position required. It makes use of the moveItemInArray and transferArrayItem we have imported from cdk dragdrop module. Now let us see the demo again in the browser − Now it allows you to drag and drop the item in the position required as shown above. The feature works very smoothly without any flicker issues and can be used in your application wherever the need arises. Print Page Previous Next Advertisements ”;

Angular7 – Forms

Angular7 – Forms ”; Previous Next In this chapter, we will see how forms are used in Angular 7. We will discuss two ways of working with forms − Template driven form Model driven form Template Driven Form With a template driven form, most of the work is done in the template. 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 button in the form. To start with, we need to import to FormsModule from @angular/forms which is done in app.module.ts as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; import { ScrollDispatchModule } from ”@angular/cdk/scrolling”; import { DragDropModule } from ”@angular/cdk/drag-drop”; import { FormsModule } from ”@angular/forms”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule, FormsModule ], 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 7 Project!”; constructor(private myservice: MyserviceService) { } ngOnInit() { } 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. The css for the login form is added in app.component.css − input[type = text], input[type = password] { width: 40%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #B3A9A9; box-sizing: border-box; } input[type = submit] { padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #B3A9A9; box-sizing: border-box; } 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 alerted as shown below − 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 { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; import { ScrollDispatchModule } from ”@angular/cdk/scrolling”; import { DragDropModule } from ”@angular/cdk/drag-drop”; import { ReactiveFormsModule } from ”@angular/forms”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule, ReactiveFormsModule ], 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 7 Project!”; emailid; formdata; constructor(private myservice: MyserviceService) { } ngOnInit() { this.formdata = new FormGroup({ emailid: new FormControl(“[email protected]”), passwd: new FormControl(“abcd1234”) }); } onClickSubmit(data) {this.emailid = data.emailid;} } The variable form data 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

Angular7 – Animations

Angular7 – Animations ”; Previous Next Animations add a lot of interaction between the html elements. Animation was available with Angular 2, from Angular 4 onwards animation is no more a part of the @angular/core library, but is a separate package that needs to be imported in app.module.ts. To start with, we need to import the library with the below line of code − import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; import { HttpClientModule } from ”@angular/common/http”; import { ScrollDispatchModule } from ”@angular/cdk/scrolling”; import { DragDropModule } from ”@angular/cdk/drag-drop”; import { ReactiveFormsModule } from ”@angular/forms”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ScrollDispatchModule, DragDropModule, ReactiveFormsModule, BrowserAnimationsModule ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } In app.component.html, we have added the html elements, which are to be animated. <div> <button (click) = “animate()”>Click Me</button> <div [@myanimation] = “state” class = “rotate”> <img src = “assets/images/img.png” width = “100” height = “100”> </div> </div> For the main div, we have added a button and a div with an image. There is a click event for which the animate function is called. And for the div, the @myanimation directive is added and given the value as state. Let us now see the app.component.ts where the animation is defined. import { Component } from ”@angular/core”; import { FormGroup, FormControl, Validators} from ”@angular/forms”; import { trigger, state, style, transition, animate } from ”@angular/animations”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”], styles:[` div { margin: 0 auto; text-align: center; width:200px; } .rotate { width:100px; height:100px; border:solid 1px red; } `], animations: [ trigger(”myanimation”,[ state(”smaller”,style({ transform : ”translateY(100px)” })), state(”larger”,style({ transform : ”translateY(0px)” })), transition(”smaller <=> larger”,animate(”300ms ease-in”)) ]) ] }) export class AppComponent { state: string = “smaller”; animate() { this.state= this.state == ”larger” ? ”smaller” : ”larger”; } } We have to import the animation function that is to be used in the .ts file as shown above. import { trigger, state, style, transition, animate } from ”@angular/animations”; Here we have imported trigger, state, style, transition, and animate from @angular/animations. Now, we will add the animations property to the @Component () decorator − animations: [ trigger(”myanimation”,[ state(”smaller”,style({ transform : ”translateY(100px)” })), state(”larger”,style({ transform : ”translateY(0px)” })), transition(”smaller <=> larger”,animate(”300ms ease-in”)) ]) ] Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied. The second param are the functions we have imported – state, transition, etc. The state function involves the animation steps, which the element will transition between. Right now we have defined two states, smaller and larger. For smaller state, we have given the style transform:translateY(100px) and transform:translateY(100px). Transition function adds animation to the html element. The first argument takes the start and end states, the second argument accepts the animate function. The animate function allows you to define the length, delay, and ease of a transition. Let us now see the .html file to see how the transition function works − <div> <button (click) = “animate()”>Click Me</button> <div [@myanimation] = “state” class = “rotate”> <img src = “assets/images/img.png” width = “100” height = “100”> </div> </div> There is a style property added in the @component directive, which centrally aligns the div. Let us consider the following example to understand the same − styles:[` div{ margin: 0 auto; text-align: center; width:200px; } .rotate{ width:100px; height:100px; border:solid 1px red; } `], Here, a special character [“] is used to add styles to the html element, if any. For the div, we have given the animation name defined in the app.component.ts file. On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows − export class AppComponent { state: string = “smaller”; animate() { this.state = this.state == ‘larger’? ”smaller” : ”larger”; } } The state variable is defined and is given the default value as smaller. The animate function changes the state on click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger. This is how the output in the browser (http://localhost:4200/) will look like − Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot − The transform function is applied in the y direction, which is changed from 0 to 100px when we click the Click Me button. The image is stored in the assets/images folder. Print Page Previous Next Advertisements ”;

Angular7 – Routing

Angular7 – 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. During the project setup, we have already included the routing module and the same is available in app.module.ts as shown below − app.module.ts 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 { } AppRoutingModule is added as shown above and included in the imports array. File details of app-routing.module are given below − import { NgModule } from ”@angular/core”; import { Routes, RouterModule } from ”@angular/router”; const routes: Routes = []; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [RouterModule] }) export class AppRoutingModule { } Here, we have to note that this file is generated by default when the routing is added during project setup. If not added, the above files have to be added manually. So in the above file, we have imported Routes and RouterModule from @angular/router. There is a const routes defined which is of type Routes. It is an array which holds all the routes we need in our project. The const routes is given to the RouterModule as shown in @NgModule. To display the routing details to the user, we need to add <router-outlet> directive where we want the view to be displayed. The same is added in app.component.html as shown below− <h1>Angular 7 Routing Demo</h1> <router-outlet></router-outlet> Now let us create 2 components called as Home and Contact Us and navigate between them using routing. Component Home First, we shall discuss about Home. Following is the syntax for Component Home − ng g component home C:projectA7angular7-app>ng g component home CREATE src/app/home/home.component.html (23 bytes) CREATE src/app/home/home.component.spec.ts (614 bytes) CREATE src/app/home/home.component.ts (261 bytes) CREATE src/app/home/home.component.css (0 bytes) UPDATE src/app/app.module.ts (692 bytes) Component Contact Us Following is the syntax for Component Contact Us − ng g component contactus C:projectA7angular7-app>ng g component contactus CREATE src/app/contactus/contactus.component.html (28 bytes) CREATE src/app/contactus/contactus.component.spec.ts (649 bytes) CREATE src/app/contactus/contactus.component.ts (281 bytes) CREATE src/app/contactus/contactus.component.css (0 bytes) UPDATE src/app/app.module.ts (786 bytes) We are done with creating components home and contact us. Below are the details of the components in app.module.ts − 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”; import { HomeComponent } from ”./home/home.component”; import { ContactusComponent } from ”./contactus/contactus.component”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, HomeComponent, ContactusComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Now let us add the routes details in app-routing.module.ts as shown below − import { NgModule } from ”@angular/core”; import { Routes, RouterModule } from ”@angular/router”; import { HomeComponent } from ”./home/home.component”; import { ContactusComponent } from ”./contactus/contactus.component”; const routes: Routes = [ {path:”home”, component:HomeComponent}, {path:”contactus”, component:ContactusComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } The routes array has the component details with path and component. The required component is imported as shown above. Here, we need to notice that the components we need for routing are imported in app.module.ts and also in app-routing.module.ts. Let us import them in one place, i.e., in app-routing.module.ts. So we will create an array of component to be used for routing and will export the array in app-routing.module.ts and again import it in app.module.ts. So we have all the components to be used for routing in app-routing.module.ts. This is how we have done it app-routing.module.ts − import { NgModule } from ”@angular/core”; import { Routes, RouterModule } from ”@angular/router”; import { HomeComponent } from ”./home/home.component”; import { ContactusComponent } from ”./contactus/contactus.component”; const routes: Routes = [ {path:”home”, component:HomeComponent}, {path:”contactus”, component:ContactusComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const RoutingComponent = [HomeComponent,ContactusComponent]; The array of components i.e., RoutingComponent is imported in app.module.ts as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule , RoutingComponent} 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, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } So now we are done with defining the routes. We need to display the same to the user, so let us add two buttons, Home and Contact Us in app.component.html and on click of the respective buttons, it will display the component view inside <router-outlet> directive which we have added in add.component.html. Create button inside app.component.html and give the path to the routes created. app.component.html <h1>Angular 7 Routing Demo</h1> <nav> <a routerLink = “/home”>Home</a> <a routerLink = “/contactus”>Contact Us </a> </nav> <router-outlet></router-outlet> In .html, we have added anchor links, Home and Contact us and used routerLink to give the path to the routes we have created in app-routing.module.ts. Let us now test the same in the browser − This is how we get it in browser. Let us add some styling to make the links look good. We have added following css in app.component.css − a:link, a:visited { background-color: #848686; color: white; padding: 10px 25px; text-align: center; text-decoration: none; display: inline-block; } a:hover, a:active { background-color: #BD9696; } This is the display of the links in the browser − Click on Home

Angular7 – Services

Angular7 – Services ”; Previous Next We might come across a situation where we need some code to be used everywhere on the page. For example, it can be for data connection that needs to be shared across components. This is achieved with the help of Services. 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 as given below − ng g service myservice C:projectA7angular7-app>ng g service myservice CREATE src/app/myservice.service.spec.ts (348 bytes) CREATE src/app/myservice.service.ts (138 bytes) The files created in app folder are as follows − Following are the files created which are shown at the bottom ― myservice.service.specs.ts and myservice.service.ts. myservice.service.ts import { Injectable } from ”@angular/core”; @Injectable({ providedIn: ”root” }) 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 { AppRoutingModule , RoutingComponent} 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”; import { MyserviceService } from ”./myservice.service”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective, RoutingComponent ], imports: [ BrowserModule, AppRoutingModule ], 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({ providedIn: ”root” }) 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 7 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 − app.component.html {{todaydate}} <app-new-cmp></app-new-cmp> Let us now see how to use the service in the new component created. 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 { newcomponent = “Entered in new component created”; todaydate; 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. Check the code highlighted. todaydate is displayed in the component html as follows − new-cmp.component.html <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({ providedIn: ”root” }) 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 7 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 check the value in the console before it is changed. Here is the app.component.html and new-cmp.component.html files − app.component.html <h3>{{todaydate}}>/h3> <h3> Service Property : {{componentproperty}}