Você está na página 1de 17

What is Angular 2? problems.

Angular is a most popular web development


framework for developing mobile apps as well
as desktop applications.

Angular framework is also utilized in the cross


platform mobile development called IONIC and so it
is not limited to web apps only.

Angular is an open source framework written and


maintained by angular team at Google and the
Father of Angular is Misko Hevery.

By Angular Developer Guide book - “Angular is a


platform and framework for building client All the Angular 2 framework code is already being
applications in HTML and TypeScript. Angular is written in ECMAScript 6.
itself written in TypeScript. It implements core and
The set of modern browsers are
optional functionality as a set of TypeScript
1. Chrome
libraries that you import into your apps.”
2. Firefox
3. Opera
4. Safari
The “Angular 2” is focusing on data-binding,
5. IE Version10, 11 and so on...
extensible HTML and on application test-ability but it
is still in design and prototyping stage.
On mobiles, it is supporting to the list of Chrome on
 Stayed Informed - What Is Angular 4 or 5 or 6?
Android, iOS 6+, Windows Phone 8+ and Fire-Fox
 Stayed Informed – Angular 2 vs. ReactJs and 13
mobile and also trying to support to older versions of
Best Advantages for Angular2
Android.
Angular framework helps us to
Angular 2 team working with Traceur compiler team
build client applications in HTML and JavaScript.
to provide the support to build some extensions. This
Angular 2 is
set of extensions called “ES 6 +A”.
so simpler, faster, modular and instrumented desig
n.
The “Angular 2” is using “Traceur”
compiler. Traceur is a compiler that takes “ES6” and
Angular 2 targeting to modern browsers and it is compiles it down (ES5) to regular JavaScript that
developing using ES6 (ES6 is runs in your browsers. It is run everywhere you want
called ECMAScript version 6). It also support to do.
to ECMAScript version 5(ES5).
Introduction to Angular 2 [A Most Popular JS
You don’t worry about the versions of ECMAScript. Framework]
The ES6 compiler manages to the versioning related Angular 2 is a most popular framework for
developing mobile apps. It is also for
desktop as well mobile applications.

The Angular 2 is focusing on data-binding,


extensible HTML and on application test-
ability but it is still in design and prototyping
stage.
versions fully supported
Angular framework helps us to build client toChrome, Firefox, Opera, Safari, and IE etc.
applications in HTML and JavaScript.
What is Traceur Compiler?
Angular 2 is so simpler, faster, modular and
instrumented design. The “Traceur” is a JavaScript compiler.

The Traceur compiler is very popular now days use


Angular 2 targeting to modern browsers and
it is developing using ES6 (The ES6 is called to allow use to use the features from the future. This
ECMAScript version 6). It also support
compiler is fully supported to ES5, ES6 and also
to ECMAScript version 5(ES5).
to vNext. The main goal of Traceur compiler is to

You don’t worry about the versions of inform to design of new JavaScript features and
ECMAScript. The compiler manages to the
versioning related problems. wrote the programming code of new efficient and
All the Angular 2 framework code is already good manners.
being written in ECMAScript 6.

What is Advantages of Angular 2?


The set of modern browsers are
1. There is many more advantage of Angular
1. Chrome
2.
2. Firefox
2. The Angular 2 has better performance.
3. Opera
3. The Angular 2 has more powerful template
4. Safari
system.
5. IE Version10 and 11.
4. The Angular 2 provide simpler APIs, lazy
Stayed Informed – 13 Best Advantages for Angular 2
loading and easier to application
debugging.
5. The Angular 2 much more testable.
On mobiles, it is supporting to the list of
6. The Angular 2 provides to nested level
Chrome on Android, iOS 6+, Windows
components.
Phone 8+ and Fire-Fox mobile and also
7. The Angular 2 execute run more than two
trying to support to older versions of Android.
programs at the same time.

The Angular 2 is using Traceur compiler to


The Angular 2 architecture diagram
generate the nice ECMAScript 5/6 that runs
identifies the eight main building blocks as.
everywhere you want to do.
1. Module
2. Component
Angular 2 team working with Traceur 3. Template
compiler team to provide the support to 4. Outpouts
build some extensions. This set of extensions 5. Data Binding
called “ES 6 +A”. 6. Directive
7. Service
8. Dependency Injection
What is ECMAScript ES5/ES6?
The Angular 2 framework consists of several
The ECMAScript is a scripting language
which is developed by Ecma International libraries, the some of them working as core
Org.
Currently ECMAScript available in multiple and some are optional.
versions that are ES5 and ES6 and both of
What Are The New Features Of Angular 2?
Why You Used Angular 2?
Angular 2 Features –
 Angular 2 is Entirely Component Based
 Directives Why You Used Angular 2?
 Dependency Injection 1. It is entirely component based.
 Used of TypeScript 2. Better change detection
 Used of Lambdas or Arrow functions 3. Angular2 has better performance.
 Generics 4. Angular2 has more powerful template system.
 Forms and Validations 5. Angular2 provide simpler APIs, lazy loading and
 And So on..... easier to application debugging.
6. Angular2 much more testable
Component Based- It is entirely component based. It 7. Angular2 provides to nested level components.
is not used to scope and controllers and Angular 2 8. Ahead of Time compilation (AOT) improves
are fully replaced by components and directives. rendering speed
9. Angular2 execute run more than two programs at
the same time.
Directives- The directive can be declared as 10. Angular1 is controllers and $scope based but
@Directive annotation. Angular2 is component based.
A component is a directive with a template and the 11. The Angular2 structural directives syntax is changed
@Component decorator is actually a @Directive like ng-repeat is replaced with *ngFor etc.
decorator extended with template oriented features. 12. In Angular2, local variables are defined using prefix
(#) hash. You can see the below *ngFor loop
Example.
Dependency Injection- Dependency Injection is a 13. TypeScript can be used for developing Angular 2
powerful pattern for managing code dependencies. applications
There are more opportunities for component and 14. Better syntax and application structure
object based to improve the dependency injection.
Best Advantages for Angular2 - [Angular 2
vs. Angular 1]
Use of TypeScript- Type represents the different
The core differences and many more advantages on
types of values which are using in the programming
Angular 2 vs. Angular 1 as following,
languages and it checks the validity of the supplied
1. It is entirely component based.
values before they are manipulated by your
2. Better change detection
programs.
3. Angular2 has better performance.
4. Angular2 has more powerful template system.
5. Angular2 provide simpler APIs, lazy loading and
Generics- TypeScript has generics which can be used
in the front-end development. easier to application debugging.
6. Angular2 much more testable
7. Angular2 provides to nested level components.
Lambdas and Arrow functions – In the TypeScript, 8. Ahead of Time compilation (AOT) improves
lambdas/ arrow functions are available. The arrow rendering speed
function is additional feature in typescript and it is 9. Angular2 execute run more than two programs at
also known as a lambda function. the same time.
10. Angular1 is controllers and $scope based but
Angular2 is component based.
Forms and Validations- Angular 2 forms and 11. The Angular2 structural directives syntax is changed
validations are an important aspect of front-end like ng-repeat is replaced with *ngFor etc.
development.
12. In Angular2, local variables are defined using prefix Bootstrapping in Angular 2,
(#) hash. You can see the below *ngFor loop import { bootstrap } from
Example. 'angular2/platform/browser';
13. TypeScript can be used for developing Angular 2 import { UsersComponent } from
applications './product.component';

14. Better syntax and application structure bootstrap(UserComponent);

The Angular2 structural directives syntax is changed


like ng-repeat is replaced with *ngFor etc.

For example as,


There are more advantages over performance, //Angular 1,
template system, application debugging, testing, <div ng-repeat="user in users">
components and nested level components. Name: {{user.name}}, Age : {{user.Age}}, Dept:
{{user.Department}}
</div>
For Examples as,
//Angular2,
Angular 1 Controller:- <div *ngFor="let user of users">
var app = angular.module("userApp", []); Name: {{user.name}}, Age : {{user.Age}}, Dept:
app.controller("productController", {{user.Department}}
function($scope) {
$scope.users = [{ name: "Anil Singh", Age:30, How To Setup Angular 2 in Visual Studio
department :"IT" }, 2017 MVC 5 / 6?
{ name: "Aradhya Singh", Age:3, department
:"MGMT" }]; How To Building Angular 2 Apps using Visual Studio
}); 2017 and MVC 6?

Angular 2 Components using TypeScript:- 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)
Here the @Component annotation is used to add the for the server application.
metadata to the class.

import { Component } from 'angular2/core'; Open Command Prompt and Follow the below
@Component({ mention Steps.
selector: 'usersdata',
template: `<h3>{{users.name}}</h3>` 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.
export class UsersComponent {
users = [{ name: "Anil Singh", Age:30,
department :"IT" }, Steps 1- C:\Users\Viainda>
{ name: "Aradhya Singh", Age:3, department Steps 2- C:\Users\Viainda>F:
:"MGMT" }]; Steps 3- F:\>
} Steps 4- F:\>mkdir Ng2DemoApp
Steps 5- F:\>cd Ng2DemoApp
Bootstrapping in Angular 1 using ng-app, Steps 6- F:\Ng2DemoApp>node --version
angular.element(document).ready(function() { v7.1.0
angular.bootstrap(document, ['userApp']);
}); Steps 7- F:\Ng2DemoApp>dotnet new --install
Microsoft.AspNetCore.SpaTemplates::*
Restoring packages for What is AOT compilation? Why Use in Angular 2?
C:\Users\Viainda\.templateengine\dotnetcli\v1
.0.3\scratch\restore.csproj...
Installing System.Xml.XPath 4.0.1. AOT compilation stands for “Ahead of Time
Steps 8- F:\Ng2DemoApp> compilation” and it are used to compiles the angular
Steps 9- F:\Ng2DemoApp>dotnet new angular components and templates to native JavaScript and
Content generation time: 2690.9577 ms HTML during the build time instead of run-time.
The template "MVC ASP.NET Core with Angular" The compiled HTML and JavaScript are deployed to
created successfully. the web server so that the compilation and render
time can be saved by the browser. It is the big
Steps 10- F:\Ng2DemoApp>dir advantage to improve the performance of
Steps 11- F:\Ng2DemoApp>dotnet restore applications.
Steps 12- F:\Ng2DemoApp>npm install

[ ..............] / fetchMetadata: sill mapToRegistry uri Advantages of AOT -


https://registry.npmjs.org/webpack-merge[ 1. Faster download: - The Angular 2 app is already
..............] - fetchMetadata: sill mapToRegistry uri compiled so it is faster.
https://registry.npmjs.org/web[ 2. Faster Rendering: - If the app is not AOT compiled
--It is taking too much time to install and after and the compilation process happens in the browser
successfully follow below steps 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
Steps 13- F:\Ng2DemoApp>start Ng2DemoApp.csproj the app. With AOT compilation, this is optimized.
3. Lesser Http Requests: - It is supporting to the lazy
loading. Actually, lazy loading is great concepts for
sending HTTP request to the server. It is minimise the
multiple requests for each associated html and css,
there is a separate request goes to the server.
4. Detect error at build time: - In Angular 2, the
compilation happens beforehand and most of the
errors can be detected at the compile time and this
process providing us a better application’s stability.

Disadvantages of AOT -
Steps 14- 1. AOT only works only with HTML and CSS and not for
After press F5 key on project to displays on your other file types. If required other file types that time
browser with “Hello, world!”. we will need to follow the previous build step.
2. We need to maintain AOT version of bootstrap file.

3. We need to clean-up step before compiling.

Angular 2 - What is Lazy Loading and How to


enable Lazy Loading?
What is lazy loading and How to enable lazy loading in
angular 2?

Lazy Loading - Lazy loading enables us to load only


the module user is interacting and keep the rest to be
What is AOT Compilation? - Pros and Cons loaded at run-time on demand.
of Ahead-of-Time!
If you are using external resources like HTML, CSS,
Lazy loading speeds up the application initial load which is coming from outside the application in case
time by splitting the code into multiple bundles and you follow best practice/cleanly your apps.
loading them on demand.
Introduction to Angular 2

1. Each and every Angular2 application must have one The Angular 2 is focusing on data-binding,
main module that is called “AppModule” and your extensible HTML and on application test-
code should be splitted into various child modules ability but it is still in design and prototyping
based on your applications. stage.
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 Angular framework helps us to build client
array and configures the router.
4. Import module specific routing in the child module. applications in HTML and JavaScript.
5. And so on.
Angular 2 is so simpler, faster, modular and
How would you Optimize the Angular 2 instrumented design.
Application for Better Performance?
The optimizations are depends on the size of Angular 2 targeting to modern browsers and
applications, type and other factors but normally we it is developing using ES6 (The ES6 is called
consider following optimizing points i.e. ECMAScript version 6). It also support
to ECMAScript version 5(ES5).

1. Consider AOT compilation.


2. Consider lazy loading instead of fully bundled app if You don’t worry about the versions of
the app size is more. ECMAScript. The compiler manages to the
3. Keep in mind, your application is bundled and versioning related problems.
disfeatured. On mobiles, it is supporting to the list of
4. Keep in mind, your application doesn’t have un- Chrome on Android, iOS 6+, Windows
necessary import statements. Phone 8+ and Fire-Fox mobile and also
5. Keep in mind, your application’s 3rd party unused trying to support to older versions of Android.
library. If exist and not used, removed from your
application.
6. Remove your application dependencies if not The Angular 2 is using Traceur compiler to
required. generate the nice ECMAScript 5/6 that runs
everywhere you want to do.
What are the Securities Threats should we be
Aware of in Angular 2 Applications?
As like your other web applications, you should flow Angular 2 team working with Traceur
in angular 2 applications also. compiler team to provide the support to
build some extensions. This set of extensions
called “ES 6 +A”.
There are some basic guidelines to mitigate the
security risks.
1. Consider using AOT compilation.
2. Try to avoid using or injecting dynamic HTML
What is Traceur Compiler?
content to your component.
3. Try to avoid using external URLs if not trusted. The “Traceur” is a JavaScript compiler.
4. Try to prevent XSRF attack by restricting the REST
APIs. The Traceur compiler is very popular now days use
3. We can inject services across frameworks of
to allow use to use the features from the future. This Angular 1 and Angular 2 in the same
compiler is fully supported to ES5, ES6 and also application.
4. Both Angular 1's and Angular 2's
to vNext. The main goal of Traceur compiler is to data binding works across frameworks in the
same view.
inform to design of new JavaScript features and
7 Best Key Differences - Constructor Vs.
wrote the programming code of new efficient and ngOnInit
good manners. Angular 2 Constructors:-

What is Advantages of Angular 2? 1. The constructor is a default method runs when


component is being constructed.
1. There is many more advantage of Angular 2. The constructor is a typescript feature and it is
2. used only for a class instantiations and nothing to
2. The Angular 2 has better performance. do with Angular 2.
3. The Angular 2 has more powerful template 3. The constructor called first time before
system. the ngOnInit().
4. The Angular 2 provide simpler APIs, lazy Angular 2 ngOnInit:-
loading and easier to application
debugging. 1. The ngOnInit event is an Angular 2 life-cycle event
5. The Angular 2 much more testable. method that is called after the first ngOnChanges and
6. The Angular 2 provides to nested level the ngOnInit method is use to parameters defined
components. with @Input otherwise the constructor is OK.
7. The Angular 2 execute run more than two
programs at the same time. 2. The ngOnInit is called after the constructor and
ngOnInit is called after the first ngOnChanges.

The Angular 2 architecture diagram 3. The ngOnChanges is called when an input or


identifies the eight main building blocks as. output binding value changes.
1. Module
2. Component Example as,
3. Template import {Component, OnInit} from
4. Outpouts '@angular/core';
5. Data Binding
6. Directive export class App implements OnInit{
7. Service constructor(){ }
8. Dependency Injection ngOnInit(){ }
}
The Angular 2 framework consists of several
When will ngInit be called? How would you
libraries, the some of them working as core make use of ngOnInit()?
and some are optional. In Angular 1.x, ngInit is called when template is re-
rendered. In other words “ng-init” is called, when I
Angular 1 and Angular 2 Integration
take turns back to a page.
1. Angular frameworks provide the support of
mixing code of Angular 1 and Angular 2 in In Angular2, there is no “ng-init” but we can create a
the same application. ways like this using the directive and ngOnInit
2. We can write the mixing components of class. Angular 2 provides life cycle hook ngOnInit by
Angular 1 and Angular 2 in the same view. default.
The ngOnInit is invoked when the component is The constructor is a default method runs when
initialized and invoked only once when the directive component is being constructed.
is instantiated. It is a best practice to implement
these life-cycle interfaces.
According to Angular2 Doc, “The ngOnInit is called The constructor is a typescript feature and it is used
right after the directive's data-bound properties have only for a class instantiations and nothing to do with
been checked for the first time, and before any of its Angular 2.
children have been checked. It is invoked only once
when the directive is instantiated.”
The constructor called first time before the
For example as, ngOnInit().
import { Directive, Input } from '@angular/core';

@Directive({ Example as,


selector: '[ngInit]' import {Component} from 'angular2/core';
}) import {UserService} from './userService';

class NgInit { @Component({


@Input() ngInit; selector: ‘list-user’,
template: `<ul><li *ngFor="#user of
ngOnInit() { users">{{user.name}}</li></ul>`
if(this.ngInit) { this.ngInit(); } })
}
} class App_Component {
users:Array<any>;
In template as following, constructor(private _userService: UserService) {
<div *ngIf="Timer.dateTime === this.users = _userService.getUsers();
currentDateTime"> }
<div *ngIf="Timer.checked" }
[ngInit]="Start"></div>
<div *ngIf="!Timer.checked"
[ngInit]="Stop"></div>
</div>
Angular 2 ngOnInit and ngOnChanges:-
Angular 2  Component Lifecycle Hooks
The common questions ask bye most of Angular 2 The ngOnInit event is an Angular 2 life-cycle event
lovers, method that is called after the first ngOnChanges and
the ngOnInit method is use to parameters defined
with @Input otherwise the constructor is OK.
“Could anyone tell me about the usage of
ngOnInit if we already have a constructor?” but The ngOnInit is called after the constructor and
Angular 2 provides life cycle hook ngOnInit by ngOnInit is called after the first ngOnChanges.
default.
The ngOnChanges is called when an input or output
binding value changes.
Angular 2 Components and Directives has multiple
life-time hooks where we custom logic can be
executed. Examples as,
Angular 2 Constructors:- import {Component, OnInit} from
'@angular/core';
export class App implements OnInit{
constructor(){
} 3. ngDoCheck - after every run of change detection.
4. ngAfterContentInit - after component content
ngOnInit(){ initialized.
} 5. ngAfterContentChecked - after every check of
} component content.
6. ngAfterViewInit - after component's view(s) are
Angular 2 ngOnDestroy :- initialized.
7. ngAfterViewChecked - after every check of a
component's view(s).
The ngDestroy directive is called in a component 8. ngOnDestroy - just before the component is
lifecycle just before the instance of the component is destroyed.
finally destroyed.

Example as, Angular 2 Lifecycle Events Log:-


@Directive({ 1. onChanges
selector: '[destroyDirective]' 2. onInit
}) 3. doCheck
export class OnDestroyDirective implements 4. afterContentInit
OnDestroy { 5. afterContentChecked
6. afterViewInit
//Call Constructor and set hello Msg. 7. afterViewChecked
constructor() { 8. doCheck
this.helloMsg = window.setInterval(() => 9. afterContentChecked
alert('Hello, I am Anil'), 2000); 10. afterViewChecked
} 11. onChanges
12. doCheck
//Destroy to the component 13. afterContentChecked
ngOnDestroy() { 14. afterViewChecked
window.clearInterval(this.helloMsg); 15. onDestroy
}
} What is the Best way to Declare and Access
a Global Variable in Angular 2?
Steps –
Angular 2 Complete lifecycle hook interface
1. Create Global Variables.
inventory:-
2. Import and Use the Global Variables in the
Component.
3. Result

Create Global Variables :- “app.global.ts”

import { Injectable
} from '@angular/core';

@Injectable()
export class AppGlobals {
readonly baseAppUrl: string = 'http
://localhost:57431/';
1. ngOnChanges - called when an input binding value readonly baseAPIUrl: string = 'http
changes. s://api.github.com/';
2. ngOnInit - after the first ngOnChanges. }
import { Http, Response
} from '@angular/http';
Import and Use the Global Variables in the import 'rxjs/add/operator/map';
Component:- “user.component.ts”
//BEGIN-REGION - USERSERVICE
@Injectable()
import { Component, export class UserService {
Injectable} from '@angular/core'; constructor(private _http: Http) {
import { CommonModule }
} from '@angular/common';
import { HttpModule, Http getAPIUsers(apiUrl) {
} from '@angular/http'; return this._http.get(apiUrl).m
import { UserService ap((data: Response) => data.json());
} from '../service/user.service'; }
import { AppGlobals
} from '../shared/app.globals'; getAppUsers(apiUrl) {
return this._http.get(apiUrl).m
ap((data: Response) => data);
@Component({ }
selector: 'user', }
templateUrl: './user.component.html //END BEGIN – USERSERVICE
',
styleUrls:
['./user.component.css'], Result:-
providers: [UserService, AppGlobals]
})

export class UserComponent {


//USERS DECLARATIONS.
users = [];

//HOME COMPONENT CONSTRUCTOR


constructor(private userService:
UserService, private _global:
AppGlobals) { }

//GET USERS SERVICE ON PAGE LOAD.


ngOnInit() {
this.userService.getAPIUsers(th What's New in Angular 4? [Angular 4 New
is._global.baseAPIUrl + 'users/hadley/o Features]
rgs').subscribe(data =>this.users =
data); Angular 4 contains some additional Enhancement
this.userService.getAppUsers(th and Improvement. Consider the following
is._global.baseAppUrl + 'api/User/GetUs enhancements.
ers').subscribe(data => 1. Smaller & Faster Apps
console.log(data)); 2. View Engine Size Reduce
} 3. Animation Package
} 4. NgIf and ngFor Improvement
//END BEGIN – USERCOMPONENT 5. Template
6. NgIf with Else
“user.server.ts” :- 7. Use of AS keyword
8. Pipes
9. HTTP Request Simplified
import { Injectable, InjectionToken 10. Apps Testing Simplified
} from '@angular/core';
11. Introduce Meta Tags <div *ngFor="let user of users | slice:0:2 as total;
12. Added some Forms Validators Attributes index as = i">
13. Added Compare Select Options {{i+1}}/{{total.length}}: {{user.name}}
14. Enhancement in Router </div>
15. Added Optional Parameter
16. Improvement Internationalization To subscribe only once to a pipe “|” with
“async” and If a user is an observable, you
can now use to write,
1. Smaller & Faster Apps - Angular
4 applications is smaller & faster in <div *ngIf="users | async as usersModel">
comparison with Angular 2. <h2>{{ usersModel.name }}</h2> <small>{{
usersModel.age }}</small>
</div>
2. View Engine Size Reduce - Some changes
under to hood to what AOT generated
code compilation that means in Angular 4, 8. Pipes - Angular 4 introduced a new
improved the compilation time. These “titlecase” pipe “|” and use to changes the
changes reduce around 60% size in most first letter of each word into the uppercase.
cases.
The example as,
3. Animation Package- Animations now <h2>{{ 'anil singh' | titlecase }}</h2>
have their own package i.e. <!-- OUPPUT - It will display 'Anil Singh' -->
@angular/platform-browser/animations
9. Http - Adding search parameters to an
“HTTP request” has been simplified as,
4. Improvement - Some Improvement on
*ngIf and *ngFor. //Angular 4 -
http.get(`${baseUrl}/api/users`, { params: { sort:
'ascending' } });

//Angular 2-
const params = new URLSearchParams();
5. Template - The template is now ng- params.append('sort', 'ascending');
template. You should use the “ng-template” http.get(`${baseUrl}/api/users`, { search: params
tag instead of “template”. Now Angular has });
its own template tag that is called “ng-
template”. 10. Test- Angular 4, overriding a template in
a test has also been simplified as,
6. NgIf with Else – Now in Angular 4, possible
to use an else syntax as,
//Angular 4 -
<div *ngIf="user.length > 0; else TestBed.overrideTemplate(UsersComponent,
empty"><h2>Users</h2></div> '<h2>{{users.name}}</h2>');
<ng-template #empty><h2>No users.</h2></ng-
template> //Angular 2 -
TestBed.overrideComponent(UsersComponent, {
7. AS keyword – A new addition to the set: { template: '<h2>{{users.name}}</h2>' }
template syntax is the “as keyword” is use to });
simplify to the “let” syntax.
11. Service- A new service has been
introduced to easily get or update “Meta
Use of as keyword, Tags” i.e.
@Component({
selector: 'users-app', <div [ngPlural]="value">
template: `<h1>Users</h1>` <ng-template ngPluralCase="=0">there is
}) nothing</ng-template>
export class UsersAppComponent { <ng-template ngPluralCase="=1">there is
constructor(meta: Meta) { one</ng-template>
meta.addTag({ name: 'Blogger', content: 'Anil </div>
Singh' });
} What's New In Angular 5? [Angular 4 vs.
} Angular 5]
The Angular 5 Contains bunch of new features,
12. Forms Validators - One new validator
performance improvements and lot of bug fixes and
joins the existing “required”, “minLength”,
also some surprises to Angular lovers.
“maxLength” and “pattern”. An email helps
1. Make AOT the default
you validate that the input is a valid email.
2. Watch mode
3. Type checking in templates
13. Compare Select Options - A new
4. More flexible metadata
“compareWith” directive has been added
5. Remove *.ngfactory.ts files
and it used to help you compare options
6. Better error messages
from a select.
7. Smooth upgrades
8. Tree-Shakeable components
<select [compareWith]="byUId"
9. Hybrid Upgrade Application
[(ngModel)]="selectedUsers">
10. And so on...
<option *ngFor="let user of users"
What's New In Angular 6? What Are
[ngValue]="user.UId">{{user.name}}</option>
Improvements In Angular 6?
</select>
Let’s start to explore all changes of Angular 6 step by
14. Router - A new interface “paramMap” step!
and “queryParamMap” has been added
and it introduced to represent the
parameters of a URL. Added ng update - This CLI commands will update
your angular project dependencies to their latest
const uid = versions. The ng update is normal package manager
this.route.snapshot.paramMap.get('UId'); tools to identify and update other dependencies.
this.userService.get(uid).subscribe(user =>
this.name = name);
ng update
15. CanDeactivate - This “CanDeactivate”
interface now has an extra (optional) Angular 6 uses RxJS 6 - this is the third-party library
parameter and it is containing the next (RxJS) and introduces two important changes as
state. compared to RxJS 5.
1. RxJS 6 introduces a new internal package structure
16. I18n - The internationalization is tiny 2. Operator concept
improvement.
Both are requires you to update your existing code
//Angular 4-
<div [ngPlural]="value">
<ng-template ngPluralCase="0">there is To update to RxJS 6, you simply run -
nothing</ng-template> npm install --save rxjs@6
<ng-template ngPluralCase="1">there is
one</ng-template>
</div> Simply run the blow command and update your
existing Angular project-
//Angular 2-
npm install --save rxjs-compat
yourObservable.map(data => data * 2)
.throttle(...)
Alternatively, you can use the command - ng update .subscribe(...);
rxjs to update RxJS and install the rxjs-
compat package automatically.
You can use the new pipe () method,
RxJS 6 Related import paths - import { map, throttle } from 'rxjs/ope
Instead of - rators';
import { Observable } from 'rxjs/Observ
able'; yourObservable
import { Subject } from 'rxjs/Subject'; .pipe(map(data => data * 2), throttle
(...))
.subscribe(...);
Use a single import -
import { Observable, Subject } from 'rx
js'; CLI update and added a new project config file -
Instead of “.angular-cli.json” using “angular.json”
So all from rxjs/Something imports become from Now in Angular 6 new projects use an “angular.json”
one 'rxjs' file instead of “.angular-cli.json” file.

Operator imports have to change - ng update @angular/cli --from=1 --


Instead of migrate-only
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/throttle';
The above command helps you to update your
Now you can use - existing “.angular-cli.json” file to the new
import { map, throttle } from 'rxjs/ope “angular.json” file.
rators';
The “angular.json” file contains the Properties -
1. Version - This is integer file format version and it is
And currently 1.
2. newProjectRoot - This is string path where new
projects will be created.
Instead of
3. defaultProject - This is default project name used in
import 'rxjs/add/observable/of'; commands.
4. CLI - This is workspace configuration options for
Angular CLI and it contains
Now you can use - a. defaultCollection
import { of } from 'rxjs'; b. packageManager
c. warnings
d. And so on.
RxJS 6 Changes - Changed Operator Usage 5. Schematics - This is configuration options for
Schematics.
6. Projects - This is configuration options for each
Instead of- project in the workspace and it contains
import 'rxjs/add/operator/map'; a. root
import 'rxjs/add/operator/throttle'; b. sourceRoot
c. projectType //AppModule class with the @NgModule
d. prefix decorator
e. schematics
@NgModule({
f. Architect - This is the project configuration for declarations: [],
Architect targets. providers: [MyService] //My services
instances are now available across the
entire app.
The <template> deprecated, Now Angular 6
})
introduce <ng-template> –
Now in Angular 6, you should use <ng- export class AppModule {
template> instead of <template> //exporting app module
}

For example, previously you are using Use with Angular 6 released-
<template [ngIf]="IsAdmin"> //my.service.ts
<p>This template renders only if @Injectable({providedIn: 'root'})
IsAdmin is true.</p> export class MyService { }
</template>
@NgModule({
declarations: [],
Now in Angular 6, you should use <ng-template> providers: [] // Service does not
instead of <template>
need to be added here
<ng-template [ngIf]="IsAdmin">
})
<p>This template renders only if
export class AppModule {}
IsAdmin is true.</p>
</ng-template>
The second one obviously saves you some lines of
code as compare to previous code.
Service level changes (the way of marking a service as
global) -
In the earlier versions, if you want to provide a Angular 6 introduces Angular Elements -
service to the entire application –you should add it The elements are a feature that allows you to
to providers [] in the AppModule but in the Angular 6 compile Angular components to native web
released you should not add in the providers [] in the components which you can use in your Angular
AppModule. application.

Example for marking a service as global - An angular element is a package which is part of the
Angular framework @angular/elements.

Instead of
//my.service.ts
export class MyService { } Angular 6 introduces new Ivy Renderer -
The new Ivy renders and it’s not stable for now and
it’s only in beta version. It will stable in future for
//In app.module.ts
production.
//JavaScript imports services
import { MyService } from './my- Ivy Renderer is new rendering engine which is
serice.service'; designed to be backward compatible with existing
render and focused to improve the speed of
rendering and it optimizes the size of the final Angular 6 introduces multiple validators for array
package. method of FormBuilder –
import { Component } from '@angular/cor
e';
The main goal of Ivy render is to speed up its loading import {FormsModule, FormBuilder, FormG
time and reduce the bundle size of your applications. roup} from '@angular/forms';
Also for uses a different approach for rendering
Angular components. constructor(private fb: FormBuilder) {}
myForm: FormGroup;
For Angular, this will not be default renderer, but you
can manually enable it in compiler options.
ngOnInit() {
this.myForm = this.fb.group({
Bazel Compiler - text: ['', Validators.required],
The Bazel Complier is a build system used for nearly options: this.fb.array([],
all software built at Google. [MyValidators.minCount, MyValidators.ma
xCount])
From Angular 6 release, will start having the Bazel });
compiler support and when you compile the code }
with Bazel Compiler, you will recompile entire code
base, but it compiles only with necessary code. Addition of navigationSource and restoredState to
NavigationStart -

The Bazel Complier uses advanced local and


distributed caching, optimized dependency analysis These two properties help us to handle multiple use
and parallel execution. cases in routing.

For more detail kindly refer the Angular 6 NgModelChange - Now emitted after value and
validity is updated on its control. Previously, it was
emitted before updated.
Replace Context, Record and Injectors -
Replace ngOutletContext with
ngTemplateOutletContext
Replace CollectionChangeRecord with As the updated value of the control is available, the
IterableChangeRecord handler will become more powerful
Now use Renderer2, Instead of Renderer

Now use StaticInjector, Instead of ReflectiveInjector, Previously -


<input [(ngModel)]="name" (ngModelChange)="onCh
ange($event)">
Angular 6 Renamed Operators -
The lists of renamed operators are –
1. do() => tap()
2. catch() => catchError() And
3. finally() => finalize()
onChange(value) {
4. switch() => switchAll()
5. throw() => throwError() console.log(value); // would log the updated value,
6. fromPromise() => from() not old value
}
Now Use - 12) Add missing lifecycle tests for projected
<input #modelDir="ngModel" [(ngModel)]="name" (n components
gModelChange)="onChange(modelDir)"> 13) Closure Compiler - Closure Compiler consistently
generates smaller bundles.
14) Rename QueryPredicate to LQuery and LQuery to
And LQueries
15) Service Worker - Service worker is a script that
onChange(NgModel: NgModel) {
runs in the web browser. It also manages caching for
console.log(NgModel.value);// would log old value, an application.
not updated value
}
16) Added multiple validators for array method of
Form Control statusChanges – Angular 6 emits an FormBuilder
event of “PENDING” when we call Abstract Control
markAsPending. 17) Handle string with and without line boundary -
Now Handle string with and without line boundary (^
& $) on pattern validators. Previously, it works with
string not boundaries.
New optional generic type ElementRef – This optional
generic type will help to get hold of the native
element of given custom Element as ElementRef 18) AbstractControl statusChanges - Previous version,
Type. not emits an event when you called “markAsPending”
but now emits an event of "PENDING" when we call
AbstractControl markAsPending.
Let’s see in depths-

19) Updates on NgModelChange - Now emitted after


1) Typescript 2.6.x supports value and validity is updated on its control.
2) Added Angular Material and CDK Stable Previously, it was emitted before updated.
3) Component Dev Kit (CDK) - CDK allows you to build
your own library of UI components using Angular 20) Allow HttpInterceptors to inject HttpClient –
Material. Previously, an interceptor attempting to inject
HttpClient directly would receive a circular
dependency error, as HttpClient was constructed via
4) Improved decorator error messages a factory which injected the interceptor instances.
5) Fix platform-detection example for Universal Users want to inject HttpClient into interceptors to
6) Ivy Renderer - It is a new backward compatible and make supporting.
main focused area - speed improvements, size
reduction, and increased flexibility.
Either HttpClient or the user has to deal specially with
the circular Dependency. This change moves that
7) Add afterContentInit and afterContentChecked to responsibility into HttpClient itself. By utilizing a new
render class HttpInterceptingHandler which lazily Loads the
8) Added to supports of nativeElement set of interceptors at request time, it's possible to
9) Added Optional generic type for ElementRef inject HttpClient directly into interceptors as
The Example looks like - construction of HttpClient no longer requires the
@ViewChild('your- interceptor chain to be constructed.
element') yourElement:ElementRef;

21) Add navigationSource and restoredState to


10) Bazel Compiler - Bazel only rebuilds what is NavigationStart – Currently, NavigationStart there is
necessary. no way to know if navigation was triggered
11) Added Test Comment imperatively or via the location change. These two
use cases 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 change).

22) Add type and hooks to directive def


23) Enable size tracking of a minimal CLI render3
application
24) Add canonical view query
25) Language Service – The 2.6 version of Typescript’s
“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/t
ag/6.0.0-beta.1

What Is Angular? What's New In Angular 6?


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

Please see the complete list of features and bug fixes


- Angular, Material and CLI -
https://github.com/angular/angular/blob/master/CH
ANGELOG.md

Você também pode gostar