Angular 8 – Animations ”; Previous Next Animation gives the web application a refreshing look and rich user interaction. In HTML, animation is basically the transformation of HTML element from one CSS style to another over a specific period of time. For example, an image element can be enlarged by changing its width and height. If the width and height of the image is changed from initial value to final value in steps over a period of time, say 10 seconds, then we get an animation effect. So, the scope of the animation depends on the feature / property provided by the CSS to style a HTML element. Angular provides a separate module BrowserAnimationModule to do the animation. BrowserAnimationModule provides an easy and clear approach to do animation. Configuring animation module Let us learn how to configure animation module in this chapter. Follow below mentioned steps to configure animation module, BrowserAnimationModule in an application. Import BrowserAnimationModule in AppModule. import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule ], declarations: [ ], bootstrap: [ ] }) export class AppModule { } Import animation function in the relevant components. import { state, style, transition, animate, trigger } from ”@angular/animations” Add animations metadata property in the relevant component. @Component({ animations: [ // animation functionality goes here ] }) export class MyAnimationComponent Concepts In angular, we need to understand the five core concept and its relationship to do animation. State State refers the specific state of the component. A component can have multiple defined state. The state is created using state() method. state() method has two arguments. name − Unique name of the state. style − Style of the state defined using style() method. animations: [ … state(”start”, style( { width: 200px; } )) … ] Here, start is the name of the state. Style Style refers the CSS style applied in a particular state. style() method is used to style the particular state of a component. It uses the CSS property and can have multiple items. animations: [ … state(”start”, style( { width: 200px; opacity: 1 } )) … ] Here, start state defines two CSS property, width with value 200px and opacity with value 1. Transition Transition refers the transition from one state to another. Animation can have multiple transition. Each transition is defined using transition() function. transition() takes two argument. Specifies the direction between two transition state. For example, start => end refers that the initial state is start and the final state is end. Actually, it is an expression with rich functionality. Specifies the animation details using animate() function. animations: [ … transition(”start => end”, [ animate(”1s”) ]) … ] Here, transition() function defines the transition from start state to end state with animation defined in animate() method. Animation Animation defines the way the transition from one state to another take place. animation() function is used to set the animation details. animate() takes a single argument in the form of below expression − duration delay easing duration − refers the duration of the transition. It is expressed as 1s, 100ms, etc., delay − refers the delay time to start the transition. It is expressed similar to duration easing − refers how do to accelerates / decelerates the transition in the given time duration. Trigger Every animation needs a trigger to start the animation. trigger() method is used to set all the animation information such as state, style, transition and animation in one place and give it a unique name. The unique name is used further to trigger the animation. animations: [ trigger(”enlarge”, [ state(”start”, style({ height: ”200px”, })), state(”end”, style({ height: ”500px”, })), transition(”start => end”, [ animate(”1s”) ]), transition(”end => start”, [ animate(”0.5s”) ]) ]), ] Here, enlarge is the unique name given to the particular animation. It has two state and related styles. It has two transition one from start to end and another from end to start. End to start state do the reverse of the animation. Trigger can be attached to an element as specified below − <div [@triggerName]=”expression”>…</div>; For example, <img [@enlarge]=”isEnlarge ? ”end” : ”start””>…</img>; Here, @enlarge − trigger is set to image tag and attrached to an expression. If isEnlarge value is changed to true, then end state will be set and it triggers start => end transition. If isEnlarge value is changed to false, then start state will be set and it triggers end => start transition. Simple Animation Example Let us write a new angular application to better understand the animation concept by enlarging an image with animation effect. Open command prompt and create new angular application. cd /go/to/workspace ng new animation-app cd animation-app Configure BrowserAnimationModule in the AppModule (src/app/app.module.ts) import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core” import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Open AppComponent (src/app/app.component.ts) and import necessary animation functions. import { state, style, transition, animate, trigger } from ”@angular/animations”; Add animation functionality, which will animate the image during the enlarging / shrinking of the image.
Category: angular8
Angular 8 – Forms
Angular 8 – Forms ”; Previous Next Forms are used to handle user input data. Angular 8 supports two types of forms. They are Template driven forms and Reactive forms. This section explains about Angular 8 forms in detail. Template driven forms Template driven forms is created using directives in the template. It is mainly used for creating a simple form application. Let’s understand how to create template driven forms in brief. Configure Forms Before understanding forms, let us learn how to configure forms in an application. To enable template driven forms, first we need to import FormsModule in app.module.ts. It is given below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule } from ”./app-routing.module”; import { AppComponent } from ”./app.component”; //import FormsModule here import { FormsModule } from ”@angular/forms”; imports: [ BrowserModule, AppRoutingModule, FormsModule //Assign FormsModule ], Once, FormsModule is imported, the application will be ready for form programming. Create simple form Let us create a sample application (template-form-app) in Angular 8 to learn the template driven form. Open command prompt and create new Angular application using below command − cd /go/to/workspace ng new template-form-app cd template-form-app Configure FormsModule in AppComponent as shown below − … import { FormsModule } from ”@angular/forms”; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Create a test component using Angular CLI as mentioned below − ng generate component test The above create a new component and the output is as follows − CREATE src/app/test/test.component.scss (0 bytes) CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) CREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545 bytes) Let’s create a simple form to display user entered text. Add the below code in test.component.html file as follows − <form #userName=”ngForm” (ngSubmit)=”onClickSubmit(userName.value)”> <input type=”text” name=”username” placeholder=”username” ngModel> <br/> <br/> <input type=”submit” value=”submit”> </form> Here, we used ngModel attribute in input text field. Create onClickSubmit() method inside test.component.ts file as shown below import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-test”, templateUrl: ”./test.component.html”, styleUrls: [”./test.component.scss”] }) export class TestComponent implements OnInit { ngOnInit() { } onClickSubmit(result) { console.log(“You have entered : ” + result.username); } } Open app.component.html and change the content as specified below − <app-test></app-test> Finally, start your application (if not done already) using the below command − ng serve Now, run your application and you could see the below response − Enter Peter in input text field and enter submit. onClickSubmit function will be called and user entered text Peter will be send as an argument. onClickSubmit will print the user name in the console and the output is as follows − Reactive Forms Reactive Forms is created inside component class so it is also referred as model driven forms. Every form control will have an object in the component and this provides greater control and flexibility in the form programming. Reactive Form is based on structured data model. Let’s understand how to use Reactive forms in angular. Configure Reactive forms To enable reactive forms, first we need to import ReactiveFormsModule in app.module.ts. It is defined below import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppRoutingModule } from ”./app-routing.module”; import { AppComponent } from ”./app.component”; import { TestComponent } from ”./test/test.component”; import { FormsModule } from ”@angular/forms”; //import ReactiveFormsModule here import { ReactiveFormsModule } from ”@angular/forms”; imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule //Assign here ] Create Reactive forms Before moving to create Reactive forms, we need to understand about the following concepts, FormControl − Define basic functionality of individual form control FormGroup − Used to aggregate the values of collection form control FormArray − Used to aggregate the values of form control into an array ControlValueAccessor − Acts as an interface between Forms API to HTML DOM elements. Let us create a sample application (reactive-form-app) in Angular 8 to learn the template driven form. Open command prompt and create new Angular application using below command − cd /go/to/workspace ng new reactive-form-app cd reactive-form-app Configure ReactiveFormsModule in AppComponent as shown below − … import { ReactiveFormsModule } from ”@angular/forms”; @NgModule({ declarations: [ AppComponent, TestComponent ], imports: [ BrowserModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Create a test component using Angular CLI as mentioned below − ng generate component test The above create a new component and the output is as follows − CREATE src/app/test/test.component.scss (0 bytes) CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) CREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545 bytes) Let’s create a simple form to display user entered text. We need to import FormGroup, FormControl classes in TestComponent. import { FormGroup, FormControl } from ”@angular/forms”; Create onClickSubmit() method inside test.component.ts file as shown below − import { Component, OnInit } from ”@angular/core”; import { FormGroup, FormControl } from ”@angular/forms”; @Component({ selector: ”app-test”, templateUrl: ”./test.component.html”, styleUrls: [”./test.component.css”] }) export class TestComponent implements OnInit { userName; formdata; ngOnInit() { this.formdata = new FormGroup({ userName: new FormControl(“Tutorialspoint”) }); } onClickSubmit(data) {this.userName = data.userName;} } Here, Created an instance of formGroup and set it to local variable, formdata. Crete an instance of FormControl and set it one of the entry in formdata. Created a onClickSubmit() method, which sets the local variable, userName with its argument. Add the below code in test.component.html file.
Angular 8 – Introduction
Angular 8 – Introduction ”; Previous Next Angular 8 is a TypeScript based full-stack web framework for building web and mobile applications. One of the major advantage is that the Angular 8 support for web application that can fit in any screen resolution. Angular application is fully compatible for mobiles, tablets, laptops or desktops. Angular 8 has an excellent user interface library for web developers which contains reusable UI components. This functionality helps us to create Single Page Applications (SPA). SPA is reactive and fast application. For example, if you have a button in single page and click on the button then the action performs dynamically in the current page without loading the new page from the server. Angular 8 is Typescript based object oriented programming and support features for server side programming as well. Comparison of angular versions As we know already, Google releases the version of Angular for the improvement of mobile and web development capabilities. All the released versions are backward compatible and can be updated easily to the newer version. Let’s go through the comparison of released versions. AngularJS AngularJs is very powerful JavaScript framework. It was released in October 2010. AngularJS based on Model View Controller (MVC) architecture and automatically handles JavaScript code suitable for each browser. Angular 2.0 Angular 2.0 was released in September 2016. It is re-engineered and rewritten version of AngularJS. AngularJs had a focus on controllers but, version 2 has changed focus on components. Components are the main building block of application. It supports features for speed in rendering, updating pages and building cross-platform native mobile apps for Google Android and iOS. Angular 4.0 Angular 4.0 was released in March 2017. It is updated to TypeScript 2.2, supports ng if-else conditions whereas Angular 2 supported only if conditions. Angular 4.0 introduces animation packages, Http search parameters and finally angular 4 applications are smaller and faster. Angular 5.0 Angular 5.0 was released in November 2017. It supported some of the salient features such as HTTPClient API, Lambda support, Improved Compiler and build optimizer. Angular 6.0 Angular 6.0 was released in May 2018. Features added to this version are updated Angular CLI, updated CDK, updated Angular Material, multiple validators and usage of reactive JS library. Angular 7.0 Angular 7.0 was released in October 2018. Some of salient features are Google supported community, POJO based development, modular structure, declarative user interface and modular structure. Angular 8 New features Angular 8 comes up with the following new attractive features − Bazel support − If your application uses several modules and libraries, Bazel concurrent builds helps to load faster in your application. Lazy loading − Angular 8 splits AppRoutingModule into smaller bundles and loads the data in the DOM. Differential loading − When you create an application, Angular CLI generates modules and this will be loaded automatically then browser will render the data. Web worker − It is running in the background, without affecting the performance of a page. Improvement of CLI workflow − Angular 8 CLI commands ng-build, ng-test and ng-run are extended to third party libraries. Router Backward Compatibility − Angular router backward compatibility feature helps to create path for larger projects so user can easily add their coding with the help of lazy coding. Opt-in usage sharing − User can opt into share Angular CLI usage data. Applications Some of the popular website using Angular Framework are listed below − Weather.com − It is one of the leading forecasting weather report website. Youtube − It is a video and sharing website hosted by Google. Netflix − It is a technology and media services provider. PayPal − It is an online payment system. Print Page Previous Next Advertisements ”;
Angular 8 – Web Workers
Angular 8 – Web Workers ”; Previous Next Web workers enables JavaScript application to run the CPU-intensive in the background so that the application main thread concentrate on the smooth operation of UI. Angular provides support for including Web workers in the application. Let us write a simple Angular application and try to use web workers. Create a new Angular application using below command − cd /go/to/workspace ng new web-worker-sample Run the application using below command − cd web-worker-sample npm run start Add new web worker using below command − ng generate web-worker app The output of the above command is as follows − CREATE tsconfig.worker.json (212 bytes) CREATE src/app/app.worker.ts (157 bytes) UPDATE tsconfig.app.json (296 bytes) UPDATE angular.json (3776 bytes) UPDATE src/app/app.component.ts (605 bytes) Here, app refers the location of the web worker to be created. Angular CLI will generate two new files, tsconfig.worker.json and src/app/app.worker.ts and update three files, tsconfig.app.json, angular.json and src/app/app.component.ts file. Let us check the changes − // tsconfig.worker.json { “extends”: “./tsconfig.json”, “compilerOptions”: { “outDir”: “./out-tsc/worker”, “lib”: [ “es2018”, “webworker” ], “types”: [] }, “include”: [ “src/**/*.worker.ts” ] } Here, tsconfig.worker.json extends tsconfig.json and includes options to compile web workers. // tsconfig.app.json [only a snippet] “exclude”: [ “src/test.ts”, “src/**/*.spec.ts”, “src/**/*.worker.ts” ] Here, Basically, it excludes all the worker from compiling as it has separate configuration. // angular.json (only a snippet) “webWorkerTsConfig”: “tsconfig.worker.json” Here, angular.json includes the web worker configuration file, tsconfig.worker.json. // src/app/app.worker.ts addEventListener(”message”, ({ data }) => { const response = `worker response to ${data}`; postMessage(response); }); Here, A web worker is created. Web worker is basically a function, which will be called when a message event is fired. The web worker will receive the data send by the caller, process it and then send the response back to the caller. // src/app/app.component.ts [only a snippet] if (typeof Worker !== ”undefined”) { // Create a new const worker = new Worker(”./app.worker”, { type: ”module” }); worker.onmessage = ({ data }) => { console.log(`page got message: ${data}`); }; worker.postMessage(”hello”); } else { // Web Workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. } Here, AppComponent create a new worker instance, create a callback function to receive the response and then post the message to the worker. Restart the application. Since the angular.json file is changed, which is not watched by Angular runner, it is necessary to restart the application. Otherwise, Angular does not identify the new web worker and does not compile it. Let us create Typescript class, src/app/app.prime.ts to find nth prime numbers. export class PrimeCalculator { static isPrimeNumber(num : number) : boolean { if(num == 1) return true; let idx : number = 2; for(idx = 2; idx < num / 2; idx++) { if(num % idx == 0) return false; } return true; } static findNthPrimeNumber(num : number) : number { let idx : number = 1; let count = 0; while(count < num) { if(this.isPrimeNumber(idx)) count++; idx++; console.log(idx); } return idx – 1; } } Here, isPrimeNumber check whether the given number is prime or not. findNthPrimeNumber finds the nth prime number. Import the new created prime number class into src/app/app.worker.ts and change the logic of the web worker to find nth prime number. /// <reference lib=”webworker” /> import { PrimeCalculator } from ”./app.prime”; addEventListener(”message”, ({ data }) => { // const response = `worker response to ${data}`; const response = PrimeCalculator.findNthPrimeNumber(parseInt(data)); postMessage(response); }); Change AppComponent and include two function, find10thPrimeNumber and find10000thPrimeNumber. import { Component } from ”@angular/core”; import { PrimeCalculator } from ”./app.prime”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Web worker sample”; prime10 : number = 0; prime10000 : number = 0; find10thPrimeNumber() { this.prime10 = PrimeCalculator.findNthPrimeNumber(10); } find10000thPrimeNumber() { if (typeof Worker !== ”undefined”) { // Create a new const worker = new Worker(”./app.worker”, { type: ”module” }); worker.onmessage = ({ data }) => { this.prime10000 = data; }; worker.postMessage(10000); } else { // Web Workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. } } } Here, find10thPrimeNumber is directly using the PrimeCalculator. But, find10000thPrimeNumber is delegating the calculation to web worker, which in turn uses PrimeCalculator. Change the AppComponent template, src/app/app.commands.html and include two option, one to find 10th prime number and another to find the 10000th prime number. <h1>{{ title }}</h1> <div> <a href=”#” (click)=”find10thPrimeNumber()”>Click here</a> to find 10th prime number <div>The 10<sup>th</sup> prime number is {{ prime10 }}</div> <br/> <a href=”#” (click)=”find10000thPrimeNumber()”>Click here</a> to find 10000th prime number <div>The 10000<sup>th</sup> prime number is {{ prime10000 }}</div> </div> Here, Finding 10000th prime number will take few seconds, but it will not affect other process as it is uses web workers. Just try to find the 10000th prime number first and then, the 10th prime number. Since, the web worker is calculating 10000th prime number, the UI does not freeze. We can check 10th prime number in the meantime. If we have not used web worker, we could not do anything in the browser as it is actively processing the 10000th prime number. The result of the application is as follows − Initial state of the application. Click and try to find the 10000th prime number and then try to find the 10th prime number. The application finds the 10th prime number quite fast and shows it. The application is still processing in the background to find
Angular 8 – Angular Components and Templates ”; Previous Next As we learned earlier, Components are building block of Angular application. The main job of Angular Component is to generate a section of web page called view. Every component will have an associated template and it will be used to generate views. Let us learn the basic concept of component and template in this chapter. Add a component Let us create a new component in our ExpenseManager application. Open command prompt and go to ExpenseManager application. cd /go/to/expense-manager Create a new component using ng generate component command as specified below − ng generate component expense-entry Output The output is mentioned below − CREATE src/app/expense-entry/expense-entry.component.html (28 bytes) CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes) CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes) CREATE src/app/expense-entry/expense-entry.component.css (0 bytes) UPDATE src/app/app.module.ts (431 bytes) Here, ExpenseEntryComponent is created under src/app/expense-entry folder. Component class, Template and stylesheet are created. AppModule is updated with new component. Add title property to ExpenseEntryComponent (src/app/expense-entry/expense-entry.component.ts) component. import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-expense-entry”, templateUrl: ”./expense-entry.component.html”, styleUrls: [”./expense-entry.component.css”] }) export class ExpenseEntryComponent implements OnInit { title: string; constructor() { } ngOnInit() { this.title = “Expense Entry” } } Update template, src/app/expense-entry/expense-entry.component.htmlwith below content. <p>{{ title }}</p> Open src/app/app.component.html and include newly created component. <h1>{{ title }}</h1> <app-expense-entry></app-expense-entry> Here, app-expense-entry is the selector value and it can be used as regular HTML Tag. Finally, the output of the application is as shown below − We will update the content of the component during the course of learning more about templates. Templates The integral part of Angular component is Template. It is used to generate the HTML content. Templates are plain HTML with additional functionality. Attach a template Template can be attached to Angular component using @component decorator’s meta data. Angular provides two meta data to attach template to components. templateUrl We already know how to use templateUrl. It expects the relative path of the template file. For example, AppComponent set its template as app.component.html. templateUrl: ”./app.component.html”, template template enables to place the HTML string inside the component itself. If the template content is minimal, then it will be easy to have it Component class itself for easy tracking and maintenance purpose. @Component({ selector: ”app-root”, templateUrl: `<h1>{{ title }}</h1>`, styleUrls: [”./app.component.css”] }) export class AppComponent implements OnInit { title = ”Expense Manager”; constructor(private debugService : DebugService) {} ngOnInit() { this.debugService.info(“Angular Application starts”); } } Attach Stylesheet Angular Templates can use CSS styles similar to HTML. Template gets its style information from two sources, a) from its component b) from application configuration. Component configuration Component decorator provides two option, styles and styleUrls to provide CSS style information to its template. Styles − styles option is used to place the CSS inside the component itself. styles: [”h1 { color: ”#ff0000”; }”] styleUrls − styleUrls is used to refer external CSS stylesheet. We can use multiple stylesheet as well. styleUrls: [”./app.component.css”, ”./custom_style.css”] Application configuration Angular provides an option in project configuration (angular.json) to specify the CSS stylesheets. The styles specified in angular.json will be applicable for all templates. Let us check our angular.json as shown below − { “projects”: { “expense-manager”: { “architect”: { “build”: { “builder”: “@angular-devkit/build-angular:browser”, “options”: { “outputPath”: “dist/expense-manager”, “index”: “src/index.html”, “main”: “src/main.ts”, “polyfills”: “src/polyfills.ts”, “tsConfig”: “tsconfig.app.json”, “aot”: false, “assets”: [ “src/favicon.ico”, “src/assets” ], “styles”: [ “src/styles.css” ], “scripts”: [] }, }, } }}, “defaultProject”: “expense-manager” } Here, styles option setssrc/styles.css as global CSS stylesheet. We can include any number of CSS stylesheets as it supports multiple values. Include bootstrap Let us include bootstrap into our ExpenseManager application using styles option and change the default template to use bootstrap components. Open command prompt and go to ExpenseManager application. cd /go/to/expense-manager Install bootstrap and JQuery library using below commands npm install –save [email protected] [email protected] Here, We have installed JQuery, because, bootstrap uses jquery extensively for advanced components. Option angular.json and set bootstrap and jquery library path. { “projects”: { “expense-manager”: { “architect”: { “build”: { “builder”:”@angular-devkit/build-angular:browser”, “options”: { “outputPath”: “dist/expense-manager”, “index”: “src/index.html”, “main”: “src/main.ts”, “polyfills”: “src/polyfills.ts”, “tsConfig”: “tsconfig.app.json”, “aot”: false, “assets”: [ “src/favicon.ico”, “src/assets” ], “styles”: [ “./node_modules/bootstrap/dist/css/bootstrap.css”, “src/styles.css” ], “scripts”: [ “./node_modules/jquery/dist/jquery.js”, “./node_modules/bootstrap/dist/js/bootstrap.js” ] }, }, } }}, “defaultProject”: “expense-manager” } Here, scripts option is used to include JavaScript library. JavaScript registered through scripts will be available to all Angular components in the application. Open app.component.html and change the content as specified below <!– Navigation –> <nav class=”navbar navbar-expand-lg navbar-dark bg-dark static-top”> <div class=”container”> <a class=”navbar-brand” href=”#”>{{ title }}</a> <button class=”navbar-toggler” type=”button” data-toggle=”collapse” data-target=”#navbarResponsive” aria-controls=”navbarResponsive” aria-expanded=”false” aria-label=”Toggle navigation”> <span class=”navbar-toggler-icon”> </span> </button> <div class=”collapse navbar-collapse” id=”navbarResponsive”> <ul class=”navbar-nav ml-auto”> <li class=”nav-item active”> <a class=”nav-link” href=”#”>Home <span class=”sr-only”>(current) </span> </a> </li> <li class=”nav-item”> <a class=”nav-link” href=”#”>Report</a> </li> <li class=”nav-item”> <a class=”nav-link” href=”#”>Add Expense</a> </li> <li class=”nav-item”> <a class=”nav-link” href=”#”>About</a> </li> </ul> </div> </div> </nav> <app-expense-entry></app-expense-entry> Here, Used bootstrap navigation and containers. Open src/app/expense-entry/expense-entry.component.html and place below content.
Angular 8 – Form Validation
Angular 8 – Form Validation ”; Previous Next Form validation is an important part of web application. It is used to validate whether the user input is in correct format or not. RequiredValidator Let’s perform simple required field validation in angular. Open command prompt and go to reactive-form-app. cd /go/to/reactive-form-app Replace the below code in test.component.ts file. import { Component, OnInit } from ”@angular/core”; //import validator and FormBuilder import { FormGroup, FormControl, Validators, FormBuilder } from ”@angular/forms”; @Component({ selector: ”app-test”, templateUrl: ”./test.component.html”, styleUrls: [”./test.component.css”] }) export class TestComponent implements OnInit { //Create FormGroup requiredForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm(); } //Create required field validator for name myForm() { this.requiredForm = this.fb.group({ name: [””, Validators.required ] }); } ngOnInit() { } } Here, We have used form builder to handle all the validation. Constructor is used to create a form with the validation rules. Add the below code inside test.component.html file. <div> <h2> Required Field validation </h2> <form [formGroup]=”requiredForm” novalidate> <div class=”form-group”> <label class=”center-block”>Name: <input class=”form-control” formControlName=”name”> </label> </div> <div *ngIf=”requiredForm.controls[”name”].invalid && requiredForm.controls[”name”].touched” class=”alert alert-danger”> <div *ngIf=”requiredForm.controls[”name”].errors.required”> Name is required. </div> </div> </form> <p>Form value: {{ requiredForm.value | json }}</p> <p>Form status: {{ requiredForm.status | json }}</p> </div> Here, requiredForm is called global form group object. It is a parent element. Form controls are childrens of requiredForm. Conditional statement is used to check, if a user has touched the input field but not enter the values then, it displays the error message. Finally, start your application (if not done already) using the below command − ng serve Now run your application and put focus on text box. Then, it will use show Name is required as shown below − If you enter text in the textbox, then it is validated and the output is shown below − PatternValidator PatternValidator is used to validate regex pattern. Let’s perform simple email validation. Open command prompt and to reactive-form-app. cd /go/to/reactive-form-app Replace below code in test.component.ts file − import { Component, OnInit } from ”@angular/core”; import { FormGroup, FormControl, Validators, FormBuilder } from ”@angular/forms”; @Component({ selector: ”app-test”, templateUrl: ”./test.component.html”, styleUrls: [”./test.component.css”] }) export class TestComponent implements OnInit { requiredForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm(); } myForm() { this.requiredForm = this.fb.group({ email: [””, [Validators.required, Validators.pattern(“^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$”)] ] }); } ngOnInit() { } } Here, Added email pattern validator inside the Validator. Update below code in test.component.html file − <div> <h2> Pattern validation </h2> <form [formGroup]=”requiredForm” novalidate> <div class=”form-group”> <label class=”center-block”>Email: <input class=”form-control” formControlName=”email”> </label> </div> <div *ngIf=”requiredForm.controls[”email”].invalid && requiredForm.controls[”email”].touched” class=”alert alert-danger”> <div *ngIf=”requiredForm.controls[”email”].errors.required”> Email is required. </div> </div> </form> <p>Form value: {{ requiredForm.value | json }}</p> <p>Form status: {{ requiredForm.status | json }}</p> </div> Here, we have created the email control and called email validator. Run your application and you could see the below result − Similarly, you can try yourself to perform other types of validators. Print Page Previous Next Advertisements ”;
Angular 8 – Installation
Angular 8 – Installation ”; Previous Next This chapter explains about how to install Angular 8 on your machine. Before moving to the installation, let’s verify the prerequisite first. Prerequisite As we know already, Angular is written in TypeScript. We need Node and npm to compile the files into JavaScript after that, we can deploy our application. For this purpose, Node.js must be installed in your system. Hopefully, you have installed Node.js on your machine. We can check it using the below command − node –version You could see the version of node. It is show below − v14.2.0 If Node is not installed, you can download and install by visiting the following link − https://nodejs.org/en/download/. Angular 8 installation Angular 8 CLI installation is based on very simple steps. It will take not more than five minutes to install. npm is used to install Angular 8 CLI. Once Node.js is installed, npm is also installed. If you want verify it, type the below command npm -v You could see the version below − 6.14.4 Let’s install Angular 8 CLI using npmas follows − npm install -g @angular/cli@^8.0.0 To verify Angular 8 is properly installed on your machine, type the below command − ng version You could see the following response − Angular CLI: 8.3.26 Node: 14.2.0 OS: win32 x64 Angular: … Package Version —————————————————— @angular-devkit/architect 0.803.26 @angular-devkit/core 8.3.26 @angular-devkit/schematics 8.3.26 @schematics/angular 8.3.26 @schematics/update 0.803.26 rxjs 6.4.0 Print Page Previous Next Advertisements ”;
Angular 8 – Data Binding
Angular 8 – Data Binding ”; Previous Next Data binding deals with how to bind your data from component to HTML DOM elements (Templates). We can easily interact with application without worrying about how to insert your data. We can make connections in two different ways one way and two-way binding. Before moving to this topic, let’s create a component in Angular 8. Open command prompt and create new Angular application using below command − cd /go/to/workspace ng new databind-app cd databind-app Create a test component using Angular CLI as mentioned below − ng generate component test The above create a new component and the output is as follows − CREATE src/app/test/test.component.scss (0 bytes) CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) CREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545 bytes) Run the application using below command − ng serve One-way data binding One-way data binding is a one-way interaction between component and its template. If you perform any changes in your component, then it will reflect the HTML elements. It supports the following types − String interpolation In general, String interpolation is the process of formatting or manipulating strings. In Angular, Interpolation is used to display data from component to view (DOM). It is denoted by the expression of {{ }} and also known as mustache syntax. Let’s create a simple string property in component and bind the data to view. Add the below code in test.component.ts file as follows − export class TestComponent implements OnInit { appName = “My first app in Angular 8”; } Move to test.component.html file and add the below code − <h1>{{appName}}</h1> Add the test component in your app.component.html file by replacing the existing content as follows − <app-test></app-test> Finally, start your application (if not done already) using the below command − ng serve You could see the following output on your screen − Event binding Events are actions like mouse click, double click, hover or any keyboard and mouse actions. If a user interacts with an application and performs some actions, then event will be raised. It is denoted by either parenthesis () or on-. We have different ways to bind an event to DOM element. Let’s understand one by one in brief. Component to view binding Let’s understand how simple button click even handling works. Add the following code in test.component.tsfile as follows − export class TestComponent { showData($event: any){ console.log(“button is clicked!”); if($event) { console.log($event.target); console.log($event.target.value); } } } $eventast:refersthefiredeventcdot:Inthisscenario:,ast:click ast:istheeventcdotast$event has all the information about event and the target element. Here, the target is button. $event.target property will have the target information. We have two approaches to call the component method to view (test.component.html). First one is defined below − <h2>Event Binding</h2> <button (click)=”showData($event)”>Click here</button> Alternatively, you can use prefix – on using canonical form as shown below − <button on-click = “showData()”>Click here</button> Here, we have not used $event as it is optional. Finally, start your application (if not done already) using the below command − ng serve Now, run your application and you could see the below response − Here, when the user clicks on the button, event binding understands to button click action and call component showData() method so we can conclude it is one-way binding. Property binding Property binding is used to bind the data from property of a component to DOM elements. It is denoted by []. Let’s understand with a simple example. Add the below code in test.component.ts file. export class TestComponent { userName:string = “Peter”; } Add the below changes in view test.component.html, <input type=”text” [value]=”userName”> Here, userName property is bind to an attribute of a DOM element <input> tag. Finally, start your application (if not done already) using the below command − ng serve Attribute binding Attribute binding is used to bind the data from component to HTML attributes. The syntax is as follows − <HTMLTag [attr.ATTR]=”Component data”> For example, <td [attr.colspan]=”columnSpan”> … </td> Let’s understand with a simple example. Add the below code in test.component.ts file. export class TestComponent { userName:string = “Peter”; } Add the below changes in view test.component.html, <input type=”text” [value]=”userName”> Here, userName property is bind to an attribute of a DOM element <input> tag. Finally, start your application (if not done already) using the below command − ng serve Class binding Class binding is used to bind the data from component to HTML class property. The syntax is as follows − <HTMLTag [class]=”component variable holding class name”> Class Binding provides additional functionality. If the component data is boolean, then the class will bind only when it is true. Multiple class can be provided by string (“foo bar”) as well as Array of string. Many more options are available. For example, <p [class]=”myClasses”> Let’s understand with a simple example. Add the below code in test.component.ts file, export class TestComponent { myCSSClass = “red”; applyCSSClass = false; } Add the below changes in view test.component.html. <p [class]=”myCSSClass”>This paragraph class comes from *myClass* property </p> <p [class.blue]=”applyCSSClass”>This paragraph class does not apply</p> Add the below content in test.component.css. .red { color: red; } .blue { color: blue; } Finally, start your application (if not done already) using the below command −
Creating First Application
Angular 8 – Creating First Application ”; Previous Next Let us create a simple angular application and analyse the structure of the basic angular application. Let us check whether the Angular Framework is installed in our system and the version of the installed Angular version using below command − ng –version Here, ng is the CLI application used to create, manage and run Angular Application. It written in JavaScript and runs in NodeJS environment. The result will show the details of the Angular version as specified below − Angular CLI: 8.3.26 Node: 14.2.0 OS: win32 x64 Angular: … Package Version —————————————————— @angular-devkit/architect 0.803.26 @angular-devkit/core 8.3.26 @angular-devkit/schematics 8.3.26 @schematics/angular 8.3.26 @schematics/update 0.803.26 rxjs 6.4.0 So, Angular is installed in our system and the version is 8.3.26. Let us create an Angular application to check our day to day expenses. Let us give ExpenseManageras our choice for our new application. Use below command to create the new application. cd /path/to/workspace ng new expense-manager Here, new is one of the command of the ng CLI application. It will be used to create new application. It will ask some basic question in order to create new application. It is enough to let the application choose the default choices. Regarding routing question as mentioned below, specify No. We will see how to create routing later in the Routing chapter. Would you like to add Angular routing? No Once the basic questions are answered, the ng CLI application create a new Angular application under expense-manager folder. Let us move into the our newly created application folder. cd expense-manager Let us check the partial structure of the application. The structure of the application is as follows − | favicon.ico | index.html | main.ts | polyfills.ts | styles.css | +—app | app.component.css | app.component.html | app.component.spec.ts | app.component.ts | app.module.ts | +—assets | .gitkeep | +—environments environment.prod.ts environment.ts Here, We have shown, only the most important file and folder of the application. favicon.ico and assets are application’s icon and application’s root asset folder. polyfills.ts contains standard code useful for browser compatibility. environments folder will have the application’s setting. It includes production and development setup. main.ts file contains the startup code. index.html is the application base HTML code. styles.css is the base CSS code. app folder contains the Angular application code, which will be learn elaborately in the upcoming chapters. Let us start the application using below command − ng serve 10% building 3/3 modules 0 activei wds: Project is running at http://localhost:4200/webpack-dev-server/ i wds: webpack output is served from / i wds: 404s will fallback to //index.html chunk {main} main.js, main.js.map (main) 49.2 kB [initial] [rendered] chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 269 kB [initial] [rendered] chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered] chunk {styles} styles.js, styles.js.map (styles) 9.75 kB [initial] [rendered] chunk {vendor} vendor.js, vendor.js.map (vendor) 3.81 MB [initial] [rendered] Date: 2020-05-26T05:02:14.134Z – Hash: 0dec2ff62a4247d58fe2 – Time: 12330ms ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** i wdm: Compiled successfully. Here, serve is the sub command used to compile and run the Angular application using a local development web server. ng server will start a development web server and serves the application under port, 4200. Let us fire up a browser and opens http://localhost:4200. The browser will show the application as shown below − Let us change the title of the application to better reflect our application. Open src/app/app.component.ts and change the code as specified below − export class AppComponent { title = ”Expense Manager”; } Our final application will be rendered in the browser as shown below − We will change the application and learn how to code an Angular application in the upcoming chapters. Print Page Previous Next Advertisements ”;
Angular 8 – Pipes
Angular 8 – Pipes ”; Previous Next Pipes are referred as filters. It helps to transform data and manage data within interpolation, denoted by {{ | }}. It accepts data, arrays, integers and strings as inputs which are separated by ‘|’ symbol. This chapter explains about pipes in detail. Adding parameters Create a date method in your test.component.ts file. export class TestComponent { presentDate = new Date(); } Now, add the below code in your test.component.html file. <div> Today”s date :- {{presentDate}} </div> Now, run the application, it will show the following output − Today”s date :- Mon Jun 15 2020 10:25:05 GMT+0530 (IST) Here, Date object is converted into easily readable format. Add Date pipe Let’s add date pipe in the above html file. <div> Today”s date :- {{presentDate | date }} </div> You could see the below output − Today”s date :- Jun 15, 2020 Parameters in Date We can add parameter in pipe using : character. We can show short, full or formatted dates using this parameter. Add the below code in test.component.html file. <div> short date :- {{presentDate | date:”shortDate” }} <br/> Full date :- {{presentDate | date:”fullDate” }} <br/> Formatted date:- {{presentDate | date:”M/dd/yyyy”}} <br/> Hours and minutes:- {{presentDate | date:”h:mm”}} </div> You could see the below response on your screen − short date :- 6/15/20 Full date :- Monday, June 15, 2020 Formatted date:- 6/15/2020 Hours and minutes:- 12:00 Chained pipes We can combine multiple pipes together. This will be useful when a scenario associates with more than one pipe that has to be applied for data transformation. In the above example, if you want to show the date with uppercase letters, then we can apply both Date and Uppercase pipes together. <div> Date with uppercase :- {{presentDate | date:”fullDate” | uppercase}} <br/> Date with lowercase :- {{presentDate | date:”medium” | lowercase}} <br/> </div> You could see the below response on your screen − Date with uppercase :- MONDAY, JUNE 15, 2020 Date with lowercase :- jun 15, 2020, 12:00:00 am Here, Date, Uppercase and Lowercase are pre-defined pipes. Let’s understand other types of built-in pipes in next section. Built-in Pipes Angular 8 supports the following built-in pipes. We will discuss one by one in brief. AsyncPipe If data comes in the form of observables, then Async pipe subscribes to an observable and returns the transmitted values. import { Observable, Observer } from ”rxjs”; export class TestComponent implements OnInit { timeChange = new Observable<string>((observer: Observer>string>) => { setInterval(() => observer.next(new Date().toString()), 1000); }); } Here, The Async pipe performs subscription for time changing in every one seconds and returns the result whenever gets passed to it. Main advantage is that, we don’t need to call subscribe on our timeChange and don’t worry about unsubscribe, if the component is removed. Add the below code inside your test.component.html. <div> Seconds changing in Time: {{ timeChange | async }} </div> Now, run the application, you could see the seconds changing on your screen. CurrencyPipe It is used to convert the given number into various countries currency format. Consider the below code in test.component.ts file. import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-test”, template: ` <div style=”text-align:center”> <h3> Currency Pipe</h3> <p>{{ price | currency:”EUR”:true}}</p> <p>{{ price | currency:”INR” }}</p> </div> `, styleUrls: [”./test.component.scss”] }) export class TestComponent implements OnInit { price : number = 20000; ngOnInit() { } } You could see the following output on your screen − Currency Pipe €20,000.00 ₹20,000.00 SlicePipe Slice pipe is used to return a slice of an array. It takes index as an argument. If you assign only start index, means it will print till the end of values. If you want to print specific range of values, then we can assign start and end index. We can also use negative index to access elements. Simple example is shown below − test.component.ts import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-test”, template: ` <div> <h3>Start index:- {{Fruits | slice:2}}</h3> <h4>Start and end index:- {{Fruits | slice:1:4}}</h4> <h5>Negative index:- {{Fruits | slice:-2}}</h5> <h6>Negative start and end index:- {{Fruits | slice:-4:-2}}</h6> </div> `, styleUrls: [”./test.component.scss”] }) export class TestComponent implements OnInit { Fruits = [“Apple”,”Orange”,”Grapes”,”Mango”,”Kiwi”,”Pomegranate”]; ngOnInit() { } } Now run your application and you could see the below output on your screen − Start index:- Grapes,Mango,Kiwi,Pomegranate Start and end index:- Orange,Grapes,Mango Negative index:- Kiwi,Pomegranate Negative start and end index:- Grapes,Mango Here, {{Fruits | slice:2}} means it starts from second index value Grapes to till the end of value. {{Fruits | slice:1:4}} means starts from 1 to end-1 so the result is one to third index values. {{Fruits | slice:-2}} means starts from -2 to till end because no end value is specified. Hence the result is Kiwi, Pomegranate. {{Fruits | slice:-4:-2}} means starts from negative index -4 is Grapes to end-1 which is -3 so the result of index[-4,-3] is Grapes, Mango. DecimalPipe It is used to format decimal values. It is also considered as CommonModule. Let’s understand a simple code in test.component.ts file, import { Component, OnInit } from ”@angular/core”; @Component({ selector: ”app-test”, template: ` <div style=”text-align:center”> <h3>Decimal Pipe</h3> <p> {{decimalNum1 | number}} </p> <p> {{decimalNum2 | number}} </p>