Angular 246 Basic
Angular 246 Basic
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.
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
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.
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).
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]
})
//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.
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 -
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