What is AngularJS Angular JS is an open source JavaScript framework that is used to build web applications. It can be freely used, changed and shared by anyone. Angular Js is developed by Google. It is an excellent framework for building single phase applications and line of business applications. AngularJS is a JavaScript framework . It can be added to an HTML page with a <script> tag. AngularJS extends HTML attributes with Directives , and binds data to HTML with Expressions .
4.1. Introduction Angular is a framework for building client applications in HTML, CSS and Typescript (that compiles to JavaScript). It has changed the way we develop client side applications, by providing the possibilities to apply the best practices usually applied on server side like modular programming, separation of concerns, testability and many other, on client side .
Advantage of AngularJS Dependency Injection: Dependency Injection specifies a design pattern in which components are given their dependencies instead of hard coding them within the component. Two way data binding : AngularJS creates a two way data-binding between the select element and the orderProp model. orderProp is then used as the input for the orderBy filter. Testing: Angular JS is designed in a way that we can test right from the start. So, it is very easy to test any of its components through unit testing and end-to-end testing. Model View Controller: In Angular JS, it is very easy to develop application in a clean MVC way. You just have to split your application code into MVC components i.e. Model, View and the Controller. Directives, filters, modules, routes etc.
Evolution:
What is Angular? Angular is basically an open-source, JavaScript-based client-side framework that helps us to develop a web-based application. Single Page Application or SPA Applications
Angular is - An MVC based structure framework A Framework for developing SPA (Single Page Application) based application Support client-side templating features. Provides us a facility to perform unit tests so that our code can be tested before deployment.
The Angular Architecture – What is MVC? Have you ever wondered how Angular works under the hood? Let’s dive in! Angular is built on the Model-View-Controller (MVC) architectural pattern, which helps to organize the application’s components and make it easier to maintain and extend. In simple terms, the MVC pattern divides the application into three parts:
The Model: This represents the data and business logic of the application. It manages the data and provides functionality to access and manipulate it. The View: This is responsible for rendering the user interface of the application. It displays the data to the user and provides the necessary interaction mechanisms. The Controller: This acts as a mediator between the Model and the View. It receives user input from the View, manipulates the Model accordingly, and updates the View to reflect the changes made to the data.
Angular 8 New features Angular 8 comes up with the following new attractive features – Typescript 3.4 or above support Provide Support SVG template 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( command-line interface) 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 is 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.
4.2 What is TypeScript ? “ TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. Anders Hejlsberg, the lead architect of C# and creator of Delphi and Turbo Pascal, has worked on the development of TypeScript.”
Some Basic Syntax of TypeScript some basic syntax or annotations in Typescript in compared to the JavaScript. JavaScript TypeScript var num = 5; var num : number = 5; var num = “ Speros ”; var num : string = “Speros”; var anydata = 123; var anydata : any = 123; var list = [1,2,3]; var list : Array<number> = [1,2,3]; function square(num){ return num * num ; } function square(num : number) : number { return num * num ; }
TypeScript cannot run directly on the browser. It needs a compiler to compile the file and generate it in JavaScript file, which can run directly on the browser. The TypeScript source file is in ". ts " extension. We can use any valid ". js " file by renaming it to ". ts " file. TypeScript uses TSC ( TypeScript Compiler) compiler, which convert Typescript code (. ts file) to JavaScript (. js file).
TypeScript Vs. JavaScript SN JavaScript TypeScript 1. It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature. 2. Netscape developed it in 1995. Anders Hejlsberg developed it in 2012. 3. JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension. 4. It is directly run on the browser. It is not directly run on the browser. 5. It is just a scripting language. It supports object-oriented programming concept like classes, interfaces, inheritance, generics, etc. 6. It doesn't support optional parameters. It supports optional parameters.
7. It is interpreted language that's why it highlighted the errors at runtime. It compiles the code and highlighted errors during the development time. 8. JavaScript doesn't support modules. TypeScript gives support for modules. 9. In this, number, string are the objects. In this, number, string are the interface. 10. JavaScript doesn't support generics. TypeScript supports generics. 11. Example: <script> function addNumbers (a, b) { return a + b; } var sum = addNumbers (15, 25); document.write ('Sum of the numbers is: ' + sum); </script> Example: function addNumbers (a, b) { return a + b; } var sum = addNumbers (15, 25); console.log(' 'Sum of the numb' + sum);
Install TypeScript . To install TypeScript , enter the following command in the Terminal Window. $ npm install typescript -g //Install as a global module $ npm install typescript@latest -g //Install latest if you have an older version To verify the installation was successful, enter the command $ tsc -v in the Terminal Window.
Step 1 :Open the Text Editor and write the following code. function addNumbers (a, b) { return a + b; } var sum = addNumbers (25, 25); console.log('Sum of the numbers is: ' + sum); Step-2 Save the above file as " . ts " extension. Step-3 Compile the TypeScript code. To compile the source code, open the command prompt , and then goes to the file directory location where we saved the above file. For example, if we save the file on the desktop, go to the terminal window and type: - cd Desktop/ folder_name . Now, type the following command tsc filename.ts for compilation and press Enter . Step -4 For Execution >Node Filename .JS
Angular Architecture Angular is a model-view-controller (MVC) framework. It provides clear guidance on how the application should be structured and offers bi-directional data flow while providing real DOM.
In Angular 8, Components and services both are simply classes with decorators that mark their types and provide metadata which guide Angular to do things. Every Angular application always has at least one component known as root component that connects a page hierarchy with page DOM ( Document Object Model . AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.) Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed in a target environment. Metadata of Component class The metadata for a component class associates it with a template that defines a view. A template combines ordinary HTML with Angular directives and binding markup that allow Angular to modify the HTML display. The metadata for a service class provides the information Angular needs to make it available to components through dependency injection (DI).
Angular Prerequisites There are three main prerequisites. NodeJS Angular uses Node.js for a large part of its build environment. As a result, to get started with Angular, you will need to have Node.js installed on your system. You can head to the NodeJS official website to download the software. Install the latest version and confirm them on you command prompt by running the following commands: node--version npm --v
Angular CLI The Angular team has created a command-line interface (CLI) tool to make it easier to bootstrap and develop your Angular applications. As it significantly helps to make the process of development easier, we highly recommend using it for your initial angular projects at the least. To install the CLI, in the command prompt, type the following commands Installation: npm install -g @angular/ cli Confirmation - ng --version
Text Editor You need a text editor to write and run your code. The most popularly used integrated development environment (IDE) is Visual Studio Code (VS Code). It is a powerful source code editor that is available on Windows, macOS , and Linux platforms. Now, Let’s create our first Angular HelloWorld Application.
Creating the Angular HelloWorld Application Step 1 Create a folder for your application in the desired location on your system and open it on VSCode . Open a new terminal and type in the following command to create your app folder. ng new hello-world When the command is run, Angular creates a skeleton application under the folder. It also includes a bunch of files and other important necessities for the application. Step 2 To run the application, change the directory to the folder created, and use the ng command. cd hello-world ng serve Once run, open your browser and navigate to localhost:4200. If another application is running on that address, you can simply run the command. ng serve--port It will generate a port for you to navigate to. Typically, the browser looks something like this
You can leave the ng serve command running in the terminal, and continue making changes. If you have the application opened in your browser, it will automatically refresh each time you save your changes. This makes the development quick and iterative. Basics of an Angular App At its core, any Angular application is still a Single-Page Application (SPA), and thus its loading is triggered by a main request to the server. When we open any URL in our browser, the very first request is made to our server. This initial request is satisfied by an HTML page, which then loads the necessary JavaScript files to load both Angular as well as our application code and templates.
e2e - e2e stands for "end to end", this is the place where we can write the end to end test. node_modules - In this, you can find all the library and packages which are used in the app. src - This file is very important for development purposes. we are mostly working with this file. this file contains many file like components, assets, environment. app folder Which contains all the “modules” and “components” of your angular application. Every application has at least one “module” and one “component”. assets folder In the asset folder, we can store static assets of our application for example images, icons, and so many things. environment folder In the environment, we can store configuration settings for different environments. Basically, this folder contains two files: (1) environment.prod.ts - this file for the production environment.(2) Environment.ts - this file for the development environment. favicon.ico - This is an icon file that displays on the browser tab. index.html - This is only one index file in the angular project. all the component's view dynamically renders with this file. main.ts - This file is a TypeScript file. It is the starting point of angular application. here we can execute bootstrap to our main module.
pollyfills.ts - this file imports all scripts required for running an Angular app. style.css - This file is used for writing global CSS for the angular app. test.ts - this file is used for setting the testing environment in our app. angular- cli.json - This file contains the standard configuration file of your application editor config - this file is used when you are working in a team environment. So make sure all the programmers have the same configuration. gitignore - this file is used for exporting files and folders to/from your git repository. Karma.conf.js - This file is used for test cases for the app. Pacakge.json - this file contains all packages, dependencies, dev dependencies, name of the project, etc. tsconfig.json - this file has a bunch of settings for your TypeScript compiler, so your typescript compiler looks at the setting and based on these settings, compiles your typescript code into javascript , so that browser can understand. tslint.json -this file checks your typescript code for readability, maintainability,and functionality errors.
Root HTML - index.html <! doctype html> <html lang ="en"> <head> <meta charset ="utf-8"> <title> HelloWorld </title> <base href ="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel ="icon" type="image/x-icon" href ="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> The root component looks very pristine and neat, with barely any references or dependencies. The only main thing in this file is the <app-root> element. This is the marker for loading the application. All the application code, styles, and inline templates are dynamically injected into the index.html file at run time by the ng serve command.
Creating and Using Components in Angular Example In this example, we will learn how to create components in an Angular application from scratch. Follow the steps below to complete this example: Lets start by creating a new Angular project using the Angular CLI ng new project-name command as shown in the example below: ng new my-sample-app When you are prompted with Would you like to add Angular routing? Choose Yes by pressing Y. When you see Which stylesheet format would you like to use? Choose CSS and press Enter. After the project gets created, navigate to the project folder:cd my-sample-app Run the project by executing the following command: ng serve --open If your installation and setup was successful, you should see a default welcome page like the following on your browser, running at http://localhost:4200/:
Now, lets create a navbar component that we can re-use in many views. Open a new terminal and navigate to your project root directory and execute the following command to create a navbar component: ng generate component navbar The above command will create the following component files in src /app/ navbar / directory and will also register NavbarComponent to the src /app/ app.module.ts file: navbar.component.css navbar.component.html navbar.component.spec.ts navbar.component.ts If you go to src /app/ app.module.ts file of your Angular project, you will see entry of NavbarComponent as shown in the example below:
Now, go to src /app/ navbar / navbar.components.ts file and find the value of selector. Here, the value of selector is app- navbar as shown in the example below: src /app/ navbar / navbar.components.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app- navbar ', templateUrl : './ navbar.component.html ', styleUrls : ['./ navbar.component.css '] }) export class NavbarComponent implements OnInit { constructor() { } ngOnInit (): void { } }
Go to the root src /app/ app.component.html file and remove everything except this line <router-outlet></router-outlet>. Copy the value of selector from the newly created src /app/ navbar / navbar.components.ts file to src /app/ app.component.html . Your root src /app/ app.component.html file should look like this: <app- navbar ></app- navbar > <router-outlet></router-outlet>
Now, go to navbar component HTML view file at src /app/ navbar / navbar.component.html and add the HTML code to display navbar to it as shown in the example below: <div class=" navbar "> <a class="active" href ="#">Home</a> <a href ="#">About</a> <a href ="#">Services</a> <a href ="#">Contact</a> </div>
Next, add the following CSS to the style-sheet file of navbar component at src /app/ navbar / navbar.component.css : . navbar { background-color: rgb (82, 81, 81); overflow: hidden; } . navbar a { color: #f2f2f2; text-align: center; float: left; text-decoration: none; font-size: 16px; padding: 14px 16px; } . navbar a:hover { background-color: #f2f2f2; color: rgb (46, 45, 45); } . navbar a.active { background-color: #0446aa; color: white; }
Go to your browser and check your application page at http://localhost:4200/. The resulting page should be something like this:
Modules Angular 8 NgModules are different from other JavaScript modules. Every Angular 8 app has a root module known as AppModule . It provides the bootstrap mechanism that launches the application. Generally, every Angular 8 app contains many functional modules. Some important features of Anngular 8 Modules: Angular 8 NgModules import the functionalities form other NgModules just like other JavaScript modules. NgModules allow their own functionality to be exported and used by other NgModules . For example, if you want to use the router service in your app, you can import the Router NgModule .
Angular is a model-view-controller (MVC) framework. It provides clear guidance on how the application should be structured and offers bi-directional data flow while providing real DOM.
In Angular 8, Components and services both are simply classes with decorators that mark their types and provide metadata which guide Angular to do things. Every Angular application always has at least one component known as root component that connects a page hierarchy with page DOM ( Document Object Model . AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.) Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed in a target environment. Metadata of Component class The metadata for a component class associates it with a template that defines a view. A template combines HTML with Angular directives and binding markup that allow Angular to modify the HTML display. The metadata for a service class provides the information Angular needs to make it available to components through dependency injection (DI).
Template, Directives and Data Binding In Angular 8, a template is used to combine HTML with Angular Markup and modify HTML elements before displaying them. Template directives provide program logic, and binding markup connects your application data and the DOM. There are two types of data binding:
1. Event Binding: Event binding is used to bind events to your app and respond to user input in the target environment by updating your application data. 2. Property Binding: Property binding is used to pass data from component class and facilitates you to update values that are computed from your application data into the HTML.
Services and Dependency Injection In Angular 8, developers create a service class for data or logic that isn't associated with a specific view, and they want to share across components. Dependency Injection (DI) is used to make your component classes efficient. DI doesn't fetch data from the server, validate user input, or log directly to the console; it simply renders such tasks to services. Routing3 In Angular 8, Router is an NgModule which provides a service that facilitates developers to define a navigation path among the different application states and view hierarchies in their app. It works in the same way as a browser's navigation works. i.e.: Enter a URL in the address bar and the browser will navigate to that corresponding page. Click the link on a page and the browser will navigate to a new page. Click the browser's back or forward buttons and the browser will navigate backward or forward according to your seen history pages.