Angular is a modern framework for app development. It is essentially a structure that helps you create applications faster by providing a number of service and objects that makes things easier for app developers. The Angular is a dramatic upgrade to the previous version of the framework. It is really a rethinking of how applications should be built. One of the primary reasons for a lot of these changes is performance. So Angular apps run 3-5 times faster than the previous version.
Angular 2 is a re-written version of Angular1 and not an update. The best way to compare Angular 2 and Angular 1 is by finding out the new features in Angular 2. This way we will be able to find out the advantages of Angular 2 over Angular1 precisely. So, some of the advantages of Angular 2 are:- Whereas Angular1 was not developed with mobile base in mind.
Angular 2+
Angular1
Angular 2 is a mobile-oriented framework
Angular 2 is a versatile framework, i.e. we have more choices for languages. We can use ES5, ES6, Typescript or Dart to write an Angular 2 code
Whereas an Angular1 code can written by using only ES5, ES6 and Dart. We don’t have many choices of language in Angular1.
Nowadays, the controllers are replaced by components and Angular 2 is completely component based.
Whereas Angular1 was based on controllers whose scope is now over.
Fully Component Based- It is fully component based. It is not used to scope and controllers as it was in angular1 and Angular 2 are fully replaced by components and directives. Directives- The directive can be declared as @Directive notation. A component is a directive with a template and the @Component decorator is actually a @Directive decorator extended with template oriented features. Dependency Injection- Dependency injection is the ability to add the functionality of components at runtime It is a powerful pattern for managing code dependencies. There are more opportunities for component and object based to improve the dependency injection. Use of TypeScript- Type represents the different types of values which are using in the programming languages and it checks the validity of the supplied values before they are manipulated by your programs. Generics- TypeScript has generics which can be used in the front-end development. Lambdas and Arrow functions – In the TypeScript, lambdas/ arrow functions are available. The arrow function is additional feature in typescript and it is also known as a lambda function. Forms and Validations- Angular 2 forms and validations are an important aspect of front-end development.
Angular has the following components − Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task. Component − This can be used to bring the modules together. Templates − This is used to define the views of an Angular JS application. Metadata − This can be used to add more data to an Angular JS class. Service − This is used to create components which can be shared across the entire application.
Angular applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function. The catch function contains a link to the Error Handler function. In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue. Now, whenever you get an error it will be redirected to the error console of the browser.
Dependency injection is the ability to add the functionality of components at runtime. Let's take a look at an example and the steps used to implement dependency injection. Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module. @Injectable() export class classname { } Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator. @Component ({ providers : [classname] })
Full form of CLI is Command Line Interface, It is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell.
It is used to give the options about TypeScript used for the Angular project. { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es2015", "dom" ], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } Following are some key points to note about the above code.
The component life cycle hooks overview the life cycle sequence and the interfaces. Angular manages the life cycle of a component. Angular creates it, renders it. It can also create and render its children. It also checks when its data bound properties change. It can even destroy it before removing it from the DOM. The life cycle hook offered by angular provides the visibility into these key life moments and the ability to act when they occur. The components go through an entire set of processes or life cycle right from its initiation to the end of the application. There are a number of life cycle hooks which are listed below: – There are a number of life cycle hooks which are listed below: –
Constructors:- ngOnInit:-
Angular 2 provide life-cycle hook ngOnInit by default. The ngOnInit is invoked when the component is initialized and invoked only once when the directive is instantiated. It is a best practice to implement these life-cycle interfaces. According to Angular Doc, “The ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.”
The differences between observable and promises are:-
@Components
@Directive
@Component meta-data annotation is used to register the components.
@Directive meta-data annotation is used to register the directives.
The components are used to create UI widgets.
The directives are used to add behavior to existing DOM elements.
The components are used to split to application into smaller parts.
The directives are use to design a reusable components.
Only one component is used per DOM element
More than one directive are used per DOM element.
In the components, @View, template and templateUrl are mandatory in the components.
The directive do not have @View etc.
Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and provides it result as a service for across your application.
Angular is using services concept and it provide the multiple features to us that are,
There are four steps as, 1. Import the injectable member i.e. import {Injectable} from '@angular/core'; 2. Import the HttpModule, Http and Response members’ i.e. import { HttpModule, Http, Response } from '@angular/http'; 3. Add the @Injectable Decorator i.e. @Injectable() 4. Export to the Service class i.e. export class UserService { constructor(private _http: Http) { } .... }
There are four steps to calling a service in component as,
A directive is a custom HTML element that is used to extend the power of HTML. Angular has the following directives that get called as part of the BrowserModule module. ngIf − The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code. Syntax *ngIf = 'expression' ngFor − The ngFor element is used to elements based on the condition of the For loop. Syntax *ngFor = 'let variable of variablelist'
If the expression evaluates to true then the corresponding gets added, else the elements are not added.
The variable is a temporary variable to display the values in the variablelist.
The Angular Router enables navigation from one view to the next as users perform application tasks. There are three main components that you are using to configure routing. Routes: - The Routes is uses to describe our application's Routes. The “RouterModule.forRoot” method in the module imports to configure the router. Five concepts that need Routes Representation Syntax:- RouterModule.forRoot([ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE PARAMETER. { path: 'login', component: LoginComponent }, { path: 'registration', component: RegistrationComponent }, { path: '**', redirectTo: 'home' } ])
A template is a HTML view that tells Angular for render your components in the views. You can see the changes as below, The templates can be inline or external separate files.
Single Page Applications are web applications that show/load a single HTML page and dynamically update/changes that page as the user interacts with the app. In an SPA the page never reloads, though parts of the page may refresh. This reduces the round trips to the server to a minimum. This way application gets faster than normal. It’s a concept where we create a single shell page or master page and load the webpages inside that master page instead of loading pages from the server by doing post backs. Angular routes are used in Angular to emplement SPA.
There are three kinds of directives in Angular:
It is a databinding technique which is used to output data from TypeScript file to HTML template(view part). It uses double curly braces to display data from component to the view. See the syntax below: <h2>{{data.heading}}</h2>
Data binding automatically keeps your page up-to-date based on your application's state. You use data binding to specify things such as the source of an image, the state of a button, or data for a particular user. Types of Data Binding: The binding punctuation of [], (), [()], and the prefix specify the direction of data flow.
Property binding helps to bind value from TypeScript to the properties of HTML elements(view). Example: <div> <img [src]='imgPath' /> </div>
This is third type of data binding available in Angular which helps to make the web page interactive, Whenever user performs any action over view then this data binding helps to send the request to the controller part(TypeScript code) to perform the respective task for the action performed by the user. Example, <button (click)='addToCart(item.id)'> Add To Cart </button>
Two way data binding is the combination of property and event binding. It automatically syncronizes the data between the view and the Model(TypeScript code). Angular provides us a directive, ngModel, to achieve two-way data binding. <div class="container"> <input [(ngModel)]='location' /> <br/><h1>Entered Location: {{location}}</h1> </div>
Below are the reasons of choosing Angular for any applications: Complete Framework: Angular is a complete framwork for developing any type of web application. We don't need to depend for any basic task in the web development. It have complete ecosystem for developing apps. Google Supports: Google is behind Angular and making huge change to make it faster as compared to other frameworks. Community Suppport: Angular has bigger community support than other javascript frontend libraries/frameworks. Declarative UI: Angular uses HTML to render the UI of an application as it is a declarative language and is much easier to use than JavaScript.
Below are the few reasons:
As we know, Browser don't understands TypeScript code so we need to convert the TypeScript code to JavaScript to work on browser. The compiler takes the TypeScript code and converts it into JavaScript. This process is commonly referred to as transpiling.