Вы находитесь на странице: 1из 12

What is Angular 2?

Angular is a most popular web development framework for The “Angular 2” is using “Traceur” compiler. Traceur is a compiler
developing mobile apps as well as desktop applications. that takes “ES6” and compiles it down (ES5) to
regular JavaScript that runs in your browsers. It is run everywhere
Angular framework is also utilized in the cross platform mobile you want to do.
development called IONIC and so it is not limited to web apps only.
Introduction to Angular 2 [A Most Popular JS Framework]
Angular is an open source framework written and maintained by Angular 2 is a most popular framework for developing
angular team at Google and the Father of Angular is Misko Hevery. mobile apps. It is also for desktop as well mobile
applications.
By Angular Developer Guide book - “Angular is a platform and
framework for building client applications in HTML and The Angular 2 is focusing on data-binding,
TypeScript. Angular is itself written in TypeScript. It extensible HTML and on application test-ability but it is
implements core and optional functionality as a set of still in design and prototyping stage.
TypeScript libraries that you import into your apps.”

Angular framework helps us to build client applications


The “Angular 2” is focusing on data-binding, extensible HTML and on in HTML and JavaScript.
application test-ability but it is still in design and prototyping stage. Angular 2 is so simpler, faster, modular and instrumented
 Stayed Informed - What Is Angular 4 or 5 or 6? design.
 Stayed Informed – Angular 2 vs. ReactJs and 13 Best Advantages
for Angular2
Angular 2 targeting to modern browsers and it is
Angular framework helps us to build client applications developing using ES6 (The ES6 is called ECMAScript version
in HTML and JavaScript. 6). It also support to ECMAScript version 5(ES5).
Angular 2 is
so simpler, faster, modular and instrumented design.
You don’t worry about the versions of ECMAScript. The
compiler manages to the versioning related problems.
Angular 2 targeting to modern browsers and it is developing All the Angular 2 framework code is already being written
using ES6 (ES6 is called ECMAScript version 6). It also support in ECMAScript 6.
to ECMAScript version 5(ES5).

You don’t worry about the versions of ECMAScript. The set of modern browsers are
The ES6 compiler manages to the versioning related problems. 1. Chrome
2. Firefox
3. Opera
4. Safari
5. IE Version10 and 11.
Stayed Informed – 13 Best Advantages for Angular 2

On mobiles, it is supporting to the list of Chrome


on Android, iOS 6+, Windows Phone 8+ and Fire-
Fox mobile and also trying to support to older versions
of Android.

The Angular 2 is using Traceur compiler to generate the


nice ECMAScript 5/6 that runs everywhere you want to do.
All the Angular 2 framework code is already being written in
ECMAScript 6.
The set of modern browsers are Angular 2 team working with Traceur compiler team to
1. Chrome provide the support to build some extensions. This set of
2. Firefox extensions called “ES 6 +A”.
3. Opera
4. Safari
5. IE Version10, 11 and so on... What is ECMAScript ES5/ES6?
The ECMAScript is a scripting language which is
On mobiles, it is supporting to the list of Chrome on Android, iOS 6+, developed by Ecma International Org.
Windows Phone 8+ and Fire-Fox mobile and also trying to support to Currently ECMAScript available in multiple versions that
older versions of Android. are ES5 and ES6 and both of versions fully supported
toChrome, Firefox, Opera, Safari, and IE etc.
Angular 2 team working with Traceur compiler team to provide the
support to build some extensions. This set of extensions called “ES 6 What is Traceur Compiler?
+A”.
The “Traceur” is a JavaScript compiler. The Traceur compiler is Generics- TypeScript has generics which can be used in the front-end
very popular now days use to allow use to use the features from the development.
future. This compiler is fully supported to ES5, ES6 and also
to vNext. The main goal of Traceur compiler is to inform to design of
new JavaScript features and wrote the programming code of new Lambdas and Arrow functions – In the TypeScript, lambdas/ arrow
efficient and good manners. functions are available. The arrow function is additional feature in
What is Advantages of Angular 2? typescript and it is also known as a lambda function.
1. There is many more advantage of Angular 2.
2. The Angular 2 has better performance.
3. The Angular 2 has more powerful template system. Forms and Validations- Angular 2 forms and validations are an
4. The Angular 2 provide simpler APIs, lazy loading and important aspect of front-end development.
easier to application debugging.
5. The Angular 2 much more testable.
6. The Angular 2 provides to nested level components.
7. The Angular 2 execute run more than two programs
at the same time.
Why You Used Angular 2?
The Angular 2 architecture diagram identifies the eight 1. It is entirely component based.
main building blocks as. 2. Better change detection
1. Module 3. Angular2 has better performance.
4. Angular2 has more powerful template system.
2. Component
5. Angular2 provide simpler APIs, lazy loading and easier to
3. Template
application debugging.
4. Outpouts
6. Angular2 much more testable
5. Data Binding
7. Angular2 provides to nested level components.
6. Directive
8. Ahead of Time compilation (AOT) improves rendering speed
7. Service
9. Angular2 execute run more than two programs at the same time.
8. Dependency Injection
10. Angular1 is controllers and $scope based but Angular2 is
The Angular 2 framework consists of several libraries, the
component based.
some of them working as core and some are optional.
11. The Angular2 structural directives syntax is changed like ng-repeat
What Are The New Features Of Angular 2? Why You Used is replaced with *ngFor etc.
Angular 2? 12. In Angular2, local variables are defined using prefix (#) hash. You
Angular 2 Features – can see the below *ngFor loop Example.
 Angular 2 is Entirely Component Based 13. TypeScript can be used for developing Angular 2 applications
 Directives 14. Better syntax and application structure
 Dependency Injection
Best Advantages for Angular2 - [Angular 2 vs. Angular 1]
 Used of TypeScript
The core differences and many more advantages on Angular 2 vs.
 Used of Lambdas or Arrow functions
Angular 1 as following,
 Generics 1. It is entirely component based.
 Forms and Validations 2. Better change detection
 And So on..... 3. Angular2 has better performance.
4. Angular2 has more powerful template system.
Component Based- It is entirely component based. It is not used to 5. Angular2 provide simpler APIs, lazy loading and easier to
scope and controllers and Angular 2 are fully replaced by components application debugging.
and directives. 6. Angular2 much more testable
7. Angular2 provides to nested level components.
8. Ahead of Time compilation (AOT) improves rendering speed
Directives- The directive can be declared as @Directive annotation. 9. Angular2 execute run more than two programs at the same time.
A component is a directive with a template and the @Component 10. Angular1 is controllers and $scope based but Angular2 is
decorator is actually a @Directive decorator extended with template component based.
oriented features. 11. The Angular2 structural directives syntax is changed like ng-repeat
is replaced with *ngFor etc.
12. In Angular2, local variables are defined using prefix (#) hash. You
Dependency Injection- Dependency Injection is a powerful pattern for
can see the below *ngFor loop Example.
managing code dependencies. There are more opportunities for
13. TypeScript can be used for developing Angular 2 applications
component and object based to improve the dependency injection.
14. Better syntax and application structure
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.

There are more advantages over performance, template system,


application debugging, testing, components and nested level Open Command Prompt and Follow the below mention Steps.
components.
Note - In the below steps, Viainda is a user in my machine. So that
your end, you will see you or your user in your machine.
For Examples as,

Angular 1 Controller:- Steps 1- C:\Users\Viainda>


var app = angular.module("userApp", []); Steps 2- C:\Users\Viainda>F:
app.controller("productController", function($scope) { Steps 3- F:\>
$scope.users = [{ name: "Anil Singh", Age:30, department Steps 4- F:\>mkdir Ng2DemoApp
:"IT" }, Steps 5- F:\>cd Ng2DemoApp
{ name: "Aradhya Singh", Age:3, department :"MGMT" }]; Steps 6- F:\Ng2DemoApp>node --version
}); v7.1.0
Angular 2 Components using TypeScript:- Steps 7- F:\Ng2DemoApp>dotnet new --install
Microsoft.AspNetCore.SpaTemplates::*
Restoring packages for
Here the @Component annotation is used to add the metadata to the
C:\Users\Viainda\.templateengine\dotnetcli\v1.0.3\scrat
class.
ch\restore.csproj...
import { Component } from 'angular2/core'; Installing System.Xml.XPath 4.0.1.
@Component({ Steps 8- F:\Ng2DemoApp>
selector: 'usersdata', Steps 9- F:\Ng2DemoApp>dotnet new angular
template: `<h3>{{users.name}}</h3>` Content generation time: 2690.9577 ms
}) The template "MVC ASP.NET Core with Angular" created
successfully.
export class UsersComponent {
users = [{ name: "Anil Singh", Age:30, department :"IT" }, Steps 10- F:\Ng2DemoApp>dir
{ name: "Aradhya Singh", Age:3, department :"MGMT" }]; Steps 11- F:\Ng2DemoApp>dotnet restore
} Steps 12- F:\Ng2DemoApp>npm install

Bootstrapping in Angular 1 using ng-app, [ ..............] / fetchMetadata: sill mapToRegistry uri


angular.element(document).ready(function() { https://registry.npmjs.org/webpack-merge[ ..............] -
angular.bootstrap(document, ['userApp']); fetchMetadata: sill mapToRegistry uri
}); https://registry.npmjs.org/web[
--It is taking too much time to install and after successfully follow
Bootstrapping in Angular 2, below steps
import { bootstrap } from 'angular2/platform/browser';
import { UsersComponent } from './product.component';
Steps 13- F:\Ng2DemoApp>start Ng2DemoApp.csproj
bootstrap(UserComponent);

The Angular2 structural directives syntax is changed like ng-repeat is


replaced with *ngFor etc.

For example as,


//Angular 1,
<div ng-repeat="user in users">
Name: {{user.name}}, Age : {{user.Age}}, Dept:
{{user.Department}}
</div>

//Angular2,
<div *ngFor="let user of users"> Steps 14-
Name: {{user.name}}, Age : {{user.Age}}, Dept: After press F5 key on project to displays on your browser with “Hello,
{{user.Department}} world!”.

How To Setup Angular 2 in Visual Studio 2017 MVC 5 / 6?


How To Building Angular 2 Apps using Visual Studio 2017 and MVC 6?

This post helps us to learn how to Setup and Create an Application that
Uses Angular 2 for the client side and ASP.NET Core with single page
application (SPA) for the server application.
1. Each and every Angular2 application must have one main
module that is called “AppModule” and your code should be splitted
into various child modules based on your applications.
2. We do not require to import or declare lazily loading module in
root module.
3. Add the route to top level routing and takes routes array and
configures the router.
4. Import module specific routing in the child module.
5. And so on.

How would you Optimize the Angular 2 Application for


Better Performance?
The optimizations are depends on the size of applications, type and
What is AOT Compilation? - Pros and Cons of Ahead-of- other factors but normally we consider following optimizing points i.e.
Time!
What is AOT compilation? Why Use in Angular 2?
1. Consider AOT compilation.
2. Consider lazy loading instead of fully bundled app if the app
AOT compilation stands for “Ahead of Time compilation” and it are size is more.
used to compiles the angular components and templates to native 3. Keep in mind, your application is bundled and disfeatured.
JavaScript and HTML during the build time instead of run-time. 4. Keep in mind, your application doesn’t have un-necessary
The compiled HTML and JavaScript are deployed to the web server so import statements.
that the compilation and render time can be saved by the browser. It 5. Keep in mind, your application’s 3rd party unused library. If
is the big advantage to improve the performance of applications. exist and not used, removed from your application.
6. Remove your application dependencies if not required.

Advantages of AOT - What are the Securities Threats should we be Aware of in


1. Faster download: - The Angular 2 app is already compiled so it Angular 2 Applications?
is faster. As like your other web applications, you should flow in angular 2
2. Faster Rendering: - If the app is not AOT compiled and the applications also.
compilation process happens in the browser once the application is
fully loaded. This has a wait time for all necessary components to be
downloaded and then the time taken by the compiler to compile the There are some basic guidelines to mitigate the security risks.
app. With AOT compilation, this is optimized. 1. Consider using AOT compilation.
3. Lesser Http Requests: - It is supporting to the lazy loading. 2. Try to avoid using or injecting dynamic HTML content to your
Actually, lazy loading is great concepts for sending HTTP request to the component.
server. It is minimise the multiple requests for each associated html 3. Try to avoid using external URLs if not trusted.
and css, there is a separate request goes to the server. 4. Try to prevent XSRF attack by restricting the REST APIs.
4. Detect error at build time: - In Angular 2, the compilation
happens beforehand and most of the errors can be detected at the If you are using external resources like HTML, CSS, which is coming
compile time and this process providing us a better application’s from outside the application in case you follow best practice/cleanly
stability. your apps.

Introduction to Angular 2
Disadvantages of AOT - The Angular 2 is focusing on data-binding,
1. AOT only works only with HTML and CSS and not for other file extensible HTML and on application test-ability but it is
types. If required other file types that time we will need to follow the still in design and prototyping stage.
previous build step.
2. We need to maintain AOT version of bootstrap file.
Angular framework helps us to build client applications
3. We need to clean-up step before compiling. in HTML and JavaScript.
Angular 2 is so simpler, faster, modular and instrumented
Angular 2 - What is Lazy Loading and How to enable Lazy design.
Loading?
What is lazy loading and How to enable lazy loading in angular 2?
Angular 2 targeting to modern browsers and it is
developing using ES6 (The ES6 is called ECMAScript version
Lazy Loading - Lazy loading enables us to load only the module user is 6). It also support to ECMAScript version 5(ES5).
interacting and keep the rest to be loaded at run-time on demand.

You don’t worry about the versions of ECMAScript. The


Lazy loading speeds up the application initial load time by splitting the compiler manages to the versioning related problems.
code into multiple bundles and loading them on demand. On mobiles, it is supporting to the list of Chrome
on Android, iOS 6+, Windows Phone 8+ and Fire-
Fox mobile and also trying to support to older versions
of Android.
1. The ngOnInit event is an Angular 2 life-cycle event method that
is called after the first ngOnChanges and the ngOnInit method is use to
The Angular 2 is using Traceur compiler to generate the parameters defined with @Input otherwise the constructor is OK.
nice ECMAScript 5/6 that runs everywhere you want to do.
2. The ngOnInit is called after the constructor and ngOnInit is
called after the first ngOnChanges.
Angular 2 team working with Traceur compiler team to
provide the support to build some extensions. This set of 3. The ngOnChanges is called when an input or output binding
extensions called “ES 6 +A”. value changes.

Example as,
import {Component, OnInit} from '@angular/core';
What is Traceur Compiler?
The “Traceur” is a JavaScript compiler. The Traceur compiler is export class App implements OnInit{
very popular now days use to allow use to use the features from the constructor(){ }
future. This compiler is fully supported to ES5, ES6 and also ngOnInit(){ }
to vNext. The main goal of Traceur compiler is to inform to design of }
new JavaScript features and wrote the programming code of new
efficient and good manners. When will ngInit be called? How would you make use of
What is Advantages of Angular 2? ngOnInit()?
1. There is many more advantage of Angular 2. In Angular 1.x, ngInit is called when template is re-rendered. In other
2. The Angular 2 has better performance. words “ng-init” is called, when I take turns back to a page.
3. The Angular 2 has more powerful template system.
4. The Angular 2 provide simpler APIs, lazy loading and In Angular2, there is no “ng-init” but we can create a ways like this
easier to application debugging. using the directive and ngOnInit class. Angular 2 provides life cycle
5. The Angular 2 much more testable. hook ngOnInit by default.
6. The Angular 2 provides to nested level components.
7. The Angular 2 execute run more than two programs
The ngOnInit is invoked when the component is initialized and invoked
at the same time.
only once when the directive is instantiated. It is a best practice to
implement these life-cycle interfaces.
The Angular 2 architecture diagram identifies the eight According to Angular2 Doc, “The ngOnInit is called right after the
main building blocks as. 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
1. Module
once when the directive is instantiated.”
2. Component
3. Template
For example as,
4. Outpouts
import { Directive, Input } from '@angular/core';
5. Data Binding
6. Directive
@Directive({
7. Service selector: '[ngInit]'
8. Dependency Injection })
The Angular 2 framework consists of several libraries, the
some of them working as core and some are optional. class NgInit {
Angular 1 and Angular 2 Integration @Input() ngInit;
1. Angular frameworks provide the support of mixing
code of Angular 1 and Angular 2 in the same application. ngOnInit() {
2. We can write the mixing components of Angular 1 and if(this.ngInit) { this.ngInit(); }
Angular 2 in the same view. }
3. We can inject services across frameworks of Angular 1 }
and Angular 2 in the same application.
4. Both Angular 1's and Angular 2's data binding works In template as following,
across frameworks in the same view. <div *ngIf="Timer.dateTime === currentDateTime">
<div *ngIf="Timer.checked" [ngInit]="Start"></div>
7 Best Key Differences - Constructor Vs. ngOnInit <div *ngIf="!Timer.checked" [ngInit]="Stop"></div>
Angular 2 Constructors:- </div>

1. The constructor is a default method runs when component is Angular 2  Component Lifecycle Hooks
being constructed. The common questions ask bye most of Angular 2 lovers,
2. The constructor is a typescript feature and it is used only for a
class instantiations and nothing to do with Angular 2.
3. The constructor called first time before the ngOnInit(). “Could anyone tell me about the usage of ngOnInit if we
Angular 2 ngOnInit:- already have a constructor?” but Angular 2 provides life cycle
hook ngOnInit by default.
Angular 2 Components and Directives has multiple life-time hooks @Directive({
where we custom logic can be executed. selector: '[destroyDirective]'
Angular 2 Constructors:- })
export class OnDestroyDirective implements OnDestroy {

The constructor is a default method runs when component is being //Call Constructor and set hello Msg.
constructed. constructor() {
this.helloMsg = window.setInterval(() => alert('Hello, I am
Anil'), 2000);
The constructor is a typescript feature and it is used only for a class }
instantiations and nothing to do with Angular 2.
//Destroy to the component
ngOnDestroy() {
The constructor called first time before the ngOnInit(). window.clearInterval(this.helloMsg);
}
}
Example as,
import {Component} from 'angular2/core';
import {UserService} from './userService'; Angular 2 Complete lifecycle hook interface inventory:-

@Component({
selector: ‘list-user’,
template: `<ul><li *ngFor="#user of
users">{{user.name}}</li></ul>`
})

class App_Component {
users:Array<any>;
constructor(private _userService: UserService) {
this.users = _userService.getUsers();
}
}

Angular 2 ngOnInit and ngOnChanges:- 1. ngOnChanges - called when an input binding value changes.
2. ngOnInit - after the first ngOnChanges.
3. ngDoCheck - after every run of change detection.
The ngOnInit event is an Angular 2 life-cycle event method that is 4. ngAfterContentInit - after component content initialized.
called after the first ngOnChanges and the ngOnInit method is use to 5. ngAfterContentChecked - after every check of component
parameters defined with @Input otherwise the constructor is OK. content.
6. ngAfterViewInit - after component's view(s) are initialized.
The ngOnInit is called after the constructor and ngOnInit is called after 7. ngAfterViewChecked - after every check of a component's
the first ngOnChanges. view(s).
8. ngOnDestroy - just before the component is destroyed.
The ngOnChanges is called when an input or output binding value
changes.
Angular 2 Lifecycle Events Log:-
1. onChanges
Examples as, 2. onInit
import {Component, OnInit} from '@angular/core'; 3. doCheck
export class App implements OnInit{ 4. afterContentInit
constructor(){ 5. afterContentChecked
} 6. afterViewInit
7. afterViewChecked
ngOnInit(){ 8. doCheck
} 9. afterContentChecked
} 10. afterViewChecked
11. onChanges
Angular 2 ngOnDestroy :- 12. doCheck
13. afterContentChecked
14. afterViewChecked
The ngDestroy directive is called in a component lifecycle just before
15. onDestroy
the instance of the component is finally destroyed.
What is the Best way to Declare and Access a Global
Variable in Angular 2?
Example as,
Steps –
1. Create Global Variables. //BEGIN-REGION - USERSERVICE
2. Import and Use the Global Variables in the Component. @Injectable()
3. Result export class UserService {
constructor(private _http: Http) {
}
Create Global Variables :- “app.global.ts”
getAPIUsers(apiUrl) {
return this._http.get(apiUrl).map((data:
import { Injectable } from '@angular/core'; Response) => data.json());
}
@Injectable()
export class AppGlobals { getAppUsers(apiUrl) {
readonly baseAppUrl: string = 'http://localhos return this._http.get(apiUrl).map((data:
t:57431/'; Response) => data);
readonly baseAPIUrl: string = 'https://api.git }
hub.com/'; }
} //END BEGIN – USERSERVICE

Import and Use the Global Variables in the Component:- Result:-


“user.component.ts”

import { Component,
Injectable} from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule, Http } from '@angular/http';
import { UserService
} from '../service/user.service';
import { AppGlobals
} from '../shared/app.globals';

@Component({
selector: 'user', What's New in Angular 4? [Angular 4 New Features]
templateUrl: './user.component.html', Angular 4 contains some additional Enhancement and Improvement.
styleUrls: ['./user.component.css'], Consider the following enhancements.
providers: [UserService, AppGlobals] 1. Smaller & Faster Apps
}) 2. View Engine Size Reduce
3. Animation Package
export class UserComponent { 4. NgIf and ngFor Improvement
//USERS DECLARATIONS. 5. Template
users = []; 6. NgIf with Else
7. Use of AS keyword
//HOME COMPONENT CONSTRUCTOR 8. Pipes
constructor(private userService: 9. HTTP Request Simplified
UserService, private _global: AppGlobals) { }
10. Apps Testing Simplified
11. Introduce Meta Tags
//GET USERS SERVICE ON PAGE LOAD.
12. Added some Forms Validators Attributes
ngOnInit() {
this.userService.getAPIUsers(this._global. 13. Added Compare Select Options
baseAPIUrl + 'users/hadley/orgs').subscribe(data 14. Enhancement in Router
=>this.users = data); 15. Added Optional Parameter
this.userService.getAppUsers(this._global. 16. Improvement Internationalization
baseAppUrl + 'api/User/GetUsers').subscribe(data
=> console.log(data));
} 1. Smaller & Faster Apps - Angular 4 applications is
} smaller & faster in comparison with Angular 2.
//END BEGIN – USERCOMPONENT

“user.server.ts” :- 2. View Engine Size Reduce - Some changes under to


hood to what AOT generated code compilation that
means in Angular 4, improved the compilation time.
import { Injectable, InjectionToken These changes reduce around 60% size in most cases.
} from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
3. Animation Package- Animations now have their own //Angular 2 -
package i.e. @angular/platform-browser/animations TestBed.overrideComponent(UsersComponent, {
set: { template: '<h2>{{users.name}}</h2>' }
});
4. Improvement - Some Improvement on *ngIf and
*ngFor. 11. Service- A new service has been introduced to easily
get or update “Meta Tags” i.e.
@Component({
selector: 'users-app',
template: `<h1>Users</h1>`
5. Template - The template is now ng-template. You should })
use the “ng-template” tag instead of “template”. Now export class UsersAppComponent {
Angular has its own template tag that is called “ng- constructor(meta: Meta) {
template”. meta.addTag({ name: 'Blogger', content: 'Anil Singh' });
}
6. NgIf with Else – Now in Angular 4, possible to use an }
else syntax as,
12. Forms Validators - One new validator joins the existing
<div *ngIf="user.length > 0; else “required”, “minLength”, “maxLength” and “pattern”. An
empty"><h2>Users</h2></div> email helps you validate that the input is a valid email.
<ng-template #empty><h2>No users.</h2></ng-template>
13. Compare Select Options - A new “compareWith”
7. AS keyword – A new addition to the template syntax is directive has been added and it used to help you
the “as keyword” is use to simplify to the “let” syntax. compare options from a select.
<select [compareWith]="byUId"
[(ngModel)]="selectedUsers">
Use of as keyword, <option *ngFor="let user of users"
<div *ngFor="let user of users | slice:0:2 as total; index as = [ngValue]="user.UId">{{user.name}}</option>
i"> </select>
{{i+1}}/{{total.length}}: {{user.name}}
</div> 14. Router - A new interface “paramMap” and
“queryParamMap” has been added and it introduced to
To subscribe only once to a pipe “|” with “async” and If a represent the parameters of a URL.
user is an observable, you can now use to write,
<div *ngIf="users | async as usersModel"> const uid = this.route.snapshot.paramMap.get('UId');
<h2>{{ usersModel.name }}</h2> <small>{{ this.userService.get(uid).subscribe(user => this.name =
usersModel.age }}</small> name);
</div>
15. CanDeactivate - This “CanDeactivate” interface now
8. Pipes - Angular 4 introduced a new “titlecase” pipe “|” has an extra (optional) parameter and it is containing the
and use to changes the first letter of each word into the next state.
uppercase.
16. I18n - The internationalization is tiny improvement.
The example as, //Angular 4-
<h2>{{ 'anil singh' | titlecase }}</h2> <div [ngPlural]="value">
<!-- OUPPUT - It will display 'Anil Singh' --> <ng-template ngPluralCase="0">there is nothing</ng-
template>
9. Http - Adding search parameters to an “HTTP request” <ng-template ngPluralCase="1">there is one</ng-
has been simplified as, template>
</div>
//Angular 4 -
http.get(`${baseUrl}/api/users`, { params: { sort: 'ascending' //Angular 2-
} }); <div [ngPlural]="value">
<ng-template ngPluralCase="=0">there is nothing</ng-
//Angular 2- template>
const params = new URLSearchParams(); <ng-template ngPluralCase="=1">there is one</ng-
params.append('sort', 'ascending'); template>
http.get(`${baseUrl}/api/users`, { search: params }); </div>

10. Test- Angular 4, overriding a template in a test has What's New In Angular 5? [Angular 4 vs. Angular 5]
The Angular 5 Contains bunch of new features, performance
also been simplified as,
improvements and lot of bug fixes and also some surprises to Angular
lovers.
//Angular 4 - 1. Make AOT the default
TestBed.overrideTemplate(UsersComponent, 2. Watch mode
'<h2>{{users.name}}</h2>'); 3. Type checking in templates
4. More flexible metadata
5. Remove *.ngfactory.ts files
6. Better error messages Now you can use -
7. Smooth upgrades import { of } from 'rxjs';
8. Tree-Shakeable components
9. Hybrid Upgrade Application
10. And so on... RxJS 6 Changes - Changed Operator Usage
What's New In Angular 6? What Are Improvements In
Angular 6?
Let’s start to explore all changes of Angular 6 step by step! Instead of-
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/throttle';
Added ng update - This CLI commands will update your angular project
dependencies to their latest versions. The ng update is normal package yourObservable.map(data => data * 2)
manager tools to identify and update other dependencies. .throttle(...)
.subscribe(...);

ng update
You can use the new pipe () method,
Angular 6 uses RxJS 6 - this is the third-party library (RxJS) and import { map, throttle } from 'rxjs/operators';
introduces two important changes as compared to RxJS 5.
1. RxJS 6 introduces a new internal package structure yourObservable
.pipe(map(data => data * 2), throttle(...))
2. Operator concept
.subscribe(...);
Both are requires you to update your existing code
CLI update and added a new project config file - Instead of “.angular-
cli.json” using “angular.json”
To update to RxJS 6, you simply run -
Now in Angular 6 new projects use an “angular.json” file instead of
npm install --save rxjs@6
“.angular-cli.json” file.

Simply run the blow command and update your existing Angular
ng update @angular/cli --from=1 --migrate-only
project-
npm install --save rxjs-compat
The above command helps you to update your existing “.angular-
cli.json” file to the new “angular.json” file.
Alternatively, you can use the command - ng update rxjs to
update RxJS and install the rxjs-compat package automatically.
The “angular.json” file contains the Properties -
1. Version - This is integer file format version and it is currently 1.
RxJS 6 Related import paths -
2. newProjectRoot - This is string path where new projects will be
Instead of -
created.
import { Observable } from 'rxjs/Observable';
3. defaultProject - This is default project name used in commands.
import { Subject } from 'rxjs/Subject';
4. CLI - This is workspace configuration options for Angular CLI and
it contains
Use a single import - a. defaultCollection
import { Observable, Subject } from 'rxjs'; b. packageManager
c. warnings
So all from rxjs/Something imports become from one 'rxjs' d. And so on.
5. Schematics - This is configuration options for Schematics.
6. Projects - This is configuration options for each project in the
Operator imports have to change - workspace and it contains
Instead of a. root
import 'rxjs/add/operator/map'; b. sourceRoot
import 'rxjs/add/operator/throttle'; c. projectType
d. prefix
Now you can use - e. schematics
import { map, throttle } from 'rxjs/operators';
f. Architect - This is the project configuration for Architect targets.

And
The <template> deprecated, Now Angular 6 introduce <ng-template>

Instead of Now in Angular 6, you should use <ng-template> instead
import 'rxjs/add/observable/of'; of <template>
For example, previously you are using An angular element is a package which is part of the Angular
<template [ngIf]="IsAdmin"> framework @angular/elements.
<p>This template renders only if IsAdmin is
true.</p>
</template>
Angular 6 introduces new Ivy Renderer -
The new Ivy renders and it’s not stable for now and it’s only in beta
Now in Angular 6, you should use <ng-template> instead of version. It will stable in future for production.
<template> Ivy Renderer is new rendering engine which is designed to be
<ng-template [ngIf]="IsAdmin"> backward compatible with existing render and focused to improve the
<p>This template renders only if IsAdmin is speed of rendering and it optimizes the size of the final package.
true.</p>
</ng-template>

The main goal of Ivy render is to speed up its loading time and reduce
Service level changes (the way of marking a service as global) - the bundle size of your applications. Also for uses a different approach
In the earlier versions, if you want to provide a service to the entire for rendering Angular components.
application –you should add it to providers [] in the AppModule but
in the Angular 6 released you should not add in the providers [] in For Angular, this will not be default renderer, but you can manually
the AppModule. enable it in compiler options.

Example for marking a service as global - Bazel Compiler -


The Bazel Complier is a build system used for nearly all software built
at Google.
Instead of
//my.service.ts
export class MyService { } From Angular 6 release, will start having the Bazel compiler support
and when you compile the code with Bazel Compiler, you will
//In app.module.ts
recompile entire code base, but it compiles only with necessary code.
//JavaScript imports services
import { MyService } from './my-serice.service';
The Bazel Complier uses advanced local and distributed caching,
//AppModule class with the @NgModule decorator
@NgModule({ optimized dependency analysis and parallel execution.
declarations: [],
providers: [MyService] //My services instances
are now available across the entire app. For more detail kindly refer the Angular 6
})
export class AppModule {
//exporting app module Replace Context, Record and Injectors -
} Replace ngOutletContext with ngTemplateOutletContext
Replace CollectionChangeRecord with IterableChangeRecord
Use with Angular 6 released- Now use Renderer2, Instead of Renderer
//my.service.ts
@Injectable({providedIn: 'root'}) Now use StaticInjector, Instead of ReflectiveInjector,
export class MyService { }

@NgModule({ Angular 6 Renamed Operators -


declarations: [], The lists of renamed operators are –
providers: [] // Service does not need to be 1. do() => tap()
added here 2. catch() => catchError()
}) 3. finally() => finalize()
export class AppModule {} 4. switch() => switchAll()
5. throw() => throwError()
6. fromPromise() => from()
The second one obviously saves you some lines of code as compare to
previous code.
Angular 6 introduces multiple validators for array method of
FormBuilder –
Angular 6 introduces Angular Elements - import { Component } from '@angular/core';
The elements are a feature that allows you to compile Angular import {FormsModule, FormBuilder, FormGroup} from
components to native web components which you can use in your '@angular/forms';
Angular application.
constructor(private fb: FormBuilder) {}
myForm: FormGroup; 6) Ivy Renderer - It is a new backward compatible and main focused
area - speed improvements, size reduction, and increased flexibility.
ngOnInit() {
this.myForm = this.fb.group({
text: ['', Validators.required], 7) Add afterContentInit and afterContentChecked to render
options: this.fb.array([], 8) Added to supports of nativeElement
[MyValidators.minCount, MyValidators.maxCount]) 9) Added Optional generic type for ElementRef
}); The Example looks like -
} @ViewChild('your-element') yourElement:ElementRef;

Addition of navigationSource and restoredState to NavigationStart -


10) Bazel Compiler - Bazel only rebuilds what is necessary.
11) Added Test Comment
These two properties help us to handle multiple use cases in routing. 12) Add missing lifecycle tests for projected components
13) Closure Compiler - Closure Compiler consistently generates smaller
bundles.
NgModelChange - Now emitted after value and validity is updated on 14) Rename QueryPredicate to LQuery and LQuery to LQueries
its control. Previously, it was emitted before updated. 15) Service Worker - Service worker is a script that runs in the web
browser. It also manages caching for an application.

As the updated value of the control is available, the handler will


16) Added multiple validators for array method of FormBuilder
become more powerful
17) Handle string with and without line boundary - Now Handle string
with and without line boundary (^ & $) on pattern validators.
Previously -
Previously, it works with string not boundaries.
<input [(ngModel)]="name" (ngModelChange)="onChange($event)">

18) AbstractControl statusChanges - Previous version, not emits an


event when you called “markAsPending” but now emits an event of
And
"PENDING" when we call AbstractControl markAsPending.
onChange(value) {
console.log(value); // would log the updated value, not old value
} 19) Updates on NgModelChange - Now emitted after value and validity
is updated on its control. Previously, it was emitted before updated.
Now Use -
<input #modelDir="ngModel" [(ngModel)]="name" (ngModelChange)=
20) Allow HttpInterceptors to inject HttpClient –
"onChange(modelDir)">
Previously, an interceptor attempting to inject HttpClient directly
would receive a circular dependency error, as HttpClient was
constructed via a factory which injected the interceptor instances.
And
Users want to inject HttpClient into interceptors to make supporting.
onChange(NgModel: NgModel) {
console.log(NgModel.value);// would log old value, not updated value
}
Either HttpClient or the user has to deal specially with the circular
Dependency. This change moves that responsibility into HttpClient
Form Control statusChanges – Angular 6 emits an event of “PENDING”
itself. By utilizing a new class HttpInterceptingHandler which lazily
when we call Abstract Control markAsPending.
Loads the set of interceptors at request time, it's possible to inject
HttpClient directly into interceptors as construction of HttpClient no
longer requires the interceptor chain to be constructed.
New optional generic type ElementRef – This optional generic type will
help to get hold of the native element of given custom Element as
21) Add navigationSource and restoredState to NavigationStart –
ElementRef Type.
Currently, NavigationStart there is no way to know if navigation was
triggered imperatively or via the location change. These two use cases
Let’s see in depths- should be handled differently for a variety of use cases (e.g., scroll
position restoration). This PR adds a navigation source field and
restored navigation id (passed to navigations triggered by a URL
1) Typescript 2.6.x supports change).
2) Added Angular Material and CDK Stable
3) Component Dev Kit (CDK) - CDK allows you to build your own library
of UI components using Angular Material. 22) Add type and hooks to directive def
23) Enable size tracking of a minimal CLI render3 application
24) Add canonical view query
4) Improved decorator error messages 25) Language Service – The 2.6 version of Typescript’s
5) Fix platform-detection example for Universal “resolveModuleName” started to require paths passed to be
separated by '/' instead of being able to handle '\'.
Where to download the Angular 6
beta - https://github.com/angular/angular/releases/tag/6.0.0-beta.1

What Is Angular? What's New In


Angular 6?
What Are the Differences What Is Architecture
Between Angular 6 and Overview of Angular?
Angular 5?

Please see the complete list of features and bug fixes - Angular,
Material and CLI -
https://github.com/angular/angular/blob/master/CHANGELOG.md

Вам также может понравиться