Angular
Angular
Angular
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.”
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
//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!”.
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.
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.
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 { 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
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.
Please see the complete list of features and bug fixes - Angular,
Material and CLI -
https://github.com/angular/angular/blob/master/CHANGELOG.md