0% found this document useful (0 votes)
3 views

Angular Interview Questions

Angular 2 is a widely used web development framework for building mobile and desktop applications, focusing on data-binding, extensible HTML, and application testability. It is component-based, utilizes TypeScript, and offers features like dependency injection, lazy loading, and improved performance compared to Angular 1. Key advantages include better change detection, a powerful template system, and a simpler API structure.

Uploaded by

indhu jayan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Angular Interview Questions

Angular 2 is a widely used web development framework for building mobile and desktop applications, focusing on data-binding, extensible HTML, and application testability. It is component-based, utilizes TypeScript, and offers features like dependency injection, lazy loading, and improved performance compared to Angular 1. Key advantages include better change detection, a powerful template system, and a simpler API structure.

Uploaded by

indhu jayan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 117

What is Angular 2? 13 Best Advantages for Angular 2!

Anil Singh 12:30 PM Edit

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 applications in HTML and TypeScript. Angular is itself written in
TypeScript. It implements core and optional functionality as a set of TypeScript
libraries that you import into your apps.”

The “Angular 2” is focusing on data-binding, extensible HTML and


on application test-ability but it is still in design and prototyping stage.

 Stayed Informed - What Is Angular 4 or 5 or 6?

 Stayed Informed – Angular 2 vs. ReactJs and 13 Best Advantages for Angular2

Angular framework helps us to build client applications


in HTML and JavaScript.

Angular 2 is so simpler, faster, modular and instrumented design.

Angular 2 targeting to modern browsers and it is developing


using ES6 (ES6 is called ECMAScript version 6). It also support
to ECMAScript version 5(ES5).
You don’t worry about the versions of ECMAScript. The ES6 compiler
manages to the versioning related problems.

All the Angular 2 framework code is already being written in


ECMAScript 6.

The set of modern browsers are

1. Chrome

2. Firefox

3. Opera

4. Safari

5. IE Version10, 11 and so on...

What Are The New Features Of Angular 2? Why You


Used Angular 2?
Anil Singh 10:19 PM Edit

Angular 2 Features –

 Angular 2 is Entirely Component Based

 Directives

 Dependency Injection
 Used of TypeScript

 Used of Lambdas or Arrow functions

 Generics

 Forms and Validations

 And So on.....

Component Based- It is entirely component based. It is not used to scope and


controllers and Angular 2 are fully replaced by components and directives.

Directives- The directive can be declared as @Directive annotation.

A component is a directive with a template and the @Component decorator is


actually a @Directive decorator extended with template oriented features.

Dependency Injection- Dependency Injection is a powerful pattern for managing


code dependencies. There are more opportunities for component and object based
to improve the dependency injection.

Use of TypeScript- Type represents the different types of values which are using
in the programming languages and it checks the validity of the supplied values
before they are manipulated by your programs.

Generics- TypeScript has generics which can be used in the front-end


development.
Lambdas and Arrow functions – In the TypeScript, lambdas/ arrow functions are
available. The arrow function is additional feature in typescript and it is also known
as a lambda function.

Forms and Validations- Angular 2 forms and validations are an important aspect
of front-end development.

Why You Used Angular 2?

1. It is entirely component based.

2. Better change detection

3. Angular2 has better performance.

4. Angular2 has more powerful template system.

5. Angular2 provide simpler APIs, lazy loading and easier to application debugging.

6. Angular2 much more testable

7. Angular2 provides to nested level components.

8. Ahead of Time compilation (AOT) improves rendering speed

9. Angular2 execute run more than two programs at the same time.

10. Angular1 is controllers and $scope based but Angular2 is component based.
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 can see the
below *ngFor loop Example.

13. TypeScript can be used for developing Angular 2 applications

14. Better syntax and application structure

13 Best Advantages for Angular2 - [Angular 2 vs. Angular


1]
Anil Singh 11:28 PM Edit

Why should you use Angular 2 ? What are the Advantages of Angular
2?
Angular 2 vs. Angular 1 Angular 4 vs. Angular 2 Angular 5 vs. Angular 4 Angular 6 vs Angular 5

The core differences and many more advantages on Angular 2 vs. Angular 1 as
following,

1. It is entirely component based.

2. Better change detection

3. Angular2 has better performance.

4. Angular2 has more powerful template system.

5. Angular2 provide simpler APIs, lazy loading and easier to application debugging.

6. Angular2 much more testable

7. Angular2 provides to nested level components.

8. Ahead of Time compilation (AOT) improves rendering speed

9. Angular2 execute run more than two programs at the same time.

10. Angular1 is controllers and $scope based but Angular2 is component based.
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 can see the
below *ngFor loop Example.

13. TypeScript can be used for developing Angular 2 applications

14. Better syntax and application structure

Angular 2 - What is Lazy Loading and How to enable Lazy


Loading?
Anil Singh 11:30 PM Edit

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 loaded at run-time on demand.

Lazy loading speeds up the application initial load time by splitting the code into
multiple bundles and loading them on demand.

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?
Anil Singh 11:43 PM Edit

The optimizations are depends on the size of applications, type and other factors
but normally we consider following optimizing points i.e.

1. Consider AOT compilation.

2. Consider lazy loading instead of fully bundled app if the app size is more.

3. Keep in mind, your application is bundled and disfeatured.

4. Keep in mind, your application doesn’t have un-necessary import statements.

5. Keep in mind, your application’s 3rd party unused library. If exist and not used,
removed from your application.

6. Remove your application dependencies if not required.

What are the Securities Threats should we be Aware of in


Angular 2 Applications?
Anil Singh 11:34 PM Edit

As like your other web applications, you should flow in angular 2 applications also.

There are some basic guidelines to mitigate the security risks.

1. Consider using AOT compilation.

2. Try to avoid using or injecting dynamic HTML content to your component.

3. Try to avoid using external URLs if not trusted.

4. Try to prevent XSRF attack by restricting the REST APIs.


If you are using external resources like HTML, CSS, which is coming
from outside the application in case you follow best practice/cleanly
your apps.

Introduction to Angular 2 [A Most Popular JS Framework]


Anil Singh 9:18 PM Edit

Angular 2 is a most popular framework for developing mobile apps. It is also for
desktop as well mobile applications.

Angular 2 vs. Angular 1 Angular 4 vs. Angular 2 Angular 5 vs. Angular 4 Angular 6 vs Angular 5

The Angular 2 is focusing on data-binding, extensible HTML and on application test-


ability but it is still in design and prototyping stage.

Angular framework helps us to build client applications in HTML and JavaScript.

Angular 2 is so simpler, faster, modular and instrumented design.

Angular 2 targeting to modern browsers and it is developing using ES6 (The ES6 is called
ECMAScript version 6). It also support to ECMAScript version 5(ES5).

7 Best Key Differences - Constructor Vs. ngOnInit


[Angular 2]
Anil Singh 11:21 AM Edit

Angular 2 Constructors:-

1. The constructor is a default method runs when component is being


constructed.
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().

Stayed Informed - 13 Best Advantages for Angular 2

Angular 2 ngOnInit:-

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
parameters defined with @Input otherwise the constructor is OK.

2. The ngOnInit is called after the constructor and ngOnInit is called


after the first ngOnChanges.

3. The ngOnChanges is called when an input or output binding value


changes.

Example as,
import {Component, OnInit} from '@angular/core';

export class App implements OnInit{


constructor(){

ngOnInit(){

}
}
When will ngInit be called? How would you make use of onNgInit()?
In Angular 1.x, ngInit is called when template is re-rendered. In other
words “ng-init” is called, when I take turns back to a page.

In Angular2, there is no “ng-init” but we can create a ways like this


using the directive and ngOnInit class. Angular 2 provides life cycle
hook ngOnInit by default.

The ngOnInit is invoked when the component is initialized and


invoked only once when the directive is instantiated. It is a best
practice to implement these life-cycle interfaces.

Stayed Informed - 13 Best Advantages for Angular 2

According to Angular2 Doc, “The ngOnInit is called right after the


directive's data-bound properties have been checked for the first time,
and before any of its children have been checked. It is invoked only
once when the directive is instantiated.”

For example as,


import { Directive, Input } from '@angular/core';

@Directive({
selector: '[ngInit]'
})

class NgInit {
@Input() ngInit;

ngOnInit() {
if(this.ngInit) { this.ngInit(); }
}
}

In template as following,
<div *ngIf="Timer.dateTime === currentDateTime">
<div *ngIf="Timer.checked" [ngInit]="Start"></div>
<div *ngIf="!Timer.checked" [ngInit]="Stop"></div>
</div>

Angular 2 Component Lifecycle Hooks [Examples Also]


Anil Singh 11:14 PM Edit

The common questions ask bye most of Angular 2 lovers,


“Could anyone tell me about the usage of ngOnInit if we
already have a constructor?” but Angular 2 provides life cycle hook
ngOnInit by default.

Angular 2 Components and Directives has multiple life-time hooks


where we custom logic can be executed.

Stayed Informed - What Are Components in Angular 5,4 and 2?

Angular 2 Constructors:-

The constructor is a default method runs when component is being


constructed.

The constructor is a typescript feature and it is used only for a class


instantiations and nothing to do with Angular 2.

The constructor called first time before the ngOnInit().


Example as,
import {Component} from 'angular2/core';
import {UserService} from './userService';

@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:-

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
parameters defined with @Input otherwise the constructor is OK.

The ngOnInit is called after the constructor and ngOnInit is called after
the first ngOnChanges.

The ngOnChanges is called when an input or output binding value


changes.
Examples as,
import {Component, OnInit} from '@angular/core';
export class App implements OnInit{
constructor(){
}

ngOnInit(){
}
}

Angular 2 ngOnDestroy :-

The ngDestroy directive is called in a component lifecycle just before


the instance of the component is finally destroyed.

Example as,
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {

//Call Constructor and set hello Msg.


constructor() {
this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
}

//Destroy to the component


ngOnDestroy() {
window.clearInterval(this.helloMsg);
}
}

Angular 2 Complete lifecycle hook interface inventory:-


1. ngOnChanges - called when an input binding value changes.

2. ngOnInit - after the first ngOnChanges.

3. ngDoCheck - after every run of change detection.

4. ngAfterContentInit - after component content initialized.

5. ngAfterContentChecked - after every check of component content.

6. ngAfterViewInit - after component's view(s) are initialized.

7. ngAfterViewChecked - after every check of a component's view(s).

8. ngOnDestroy - just before the component is destroyed.

Angular 2 Lifecycle Events Log:-


1. onChanges

2. onInit

3. doCheck

4. afterContentInit

5. afterContentChecked

6. afterViewInit
7. afterViewChecked

8. doCheck

9. afterContentChecked

10. afterViewChecked

11. onChanges

12. doCheck

13. afterContentChecked

14. afterViewChecked

15. onDestroy

What is the Best way to Declare and Access a Global


Variable in Angular 2?
Anil Singh 2:08 AM Edit

This post helps us to learn “Declare and Access a Global Variable in Angular 2”
using “Typescript” and also share the steps to create and use of this global
variables.

Stayed Informed - Angular 2 Tutorials and Examples

Steps –

1. Create Global Variables.

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/';

readonly baseAPIUrl: string = 'https://api.github.com/';

Import and Use the Global Variables in the Component:-


“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',

templateUrl: './user.component.html',

styleUrls: ['./user.component.css'],

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(this._global.baseAPIUrl + 'users/hadley/
orgs').subscribe(data => this.users = data);

this.userService.getAppUsers(this._global.baseAppUrl + 'api/User/
GetUsers').subscribe(data => console.log(data));

//END BEGIN – USERCOMPONENT

“user.server.ts” :-

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

import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

//BEGIN-REGION - USERSERVICE

@Injectable()

export class UserService {

constructor(private _http: Http) {

getAPIUsers(apiUrl) {
return this._http.get(apiUrl).map((data: Response) => data.json());

getAppUsers(apiUrl) {

return this._http.get(apiUrl).map((data: Response) => data);

//END BEGIN – USERSERVICE

What's New in Angular 4? [Angular 4 New Features]


Anil Singh 8:45 PM Edit

Angular 4 contains some additional Enhancement and Improvement.


Consider the following enhancements.
1. Smaller & Faster Apps
2. View Engine Size Reduce
3. Animation Package
4. NgIf and ngFor Improvement
5. Template
6. NgIf with Else
7. Use of AS keyword
8. Pipes
9. HTTP Request Simplified
10. Apps Testing Simplified
11. Introduce Meta Tags
12. Added some Forms Validators Attributes
13. Added Compare Select Options
14. Enhancement in Router
15. Added Optional Parameter
16. Improvement Internationalization
1. Smaller & Faster Apps - Angular 4 applications is smaller & faster in
comparison with Angular 2.

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. These changes reduce around 60% size in most cases.

3. Animation Package- Animations now have their own package i.e.


@angular/platform-browser/animations

4. Improvement - Some Improvement on *ngIf and *ngFor.

5. Template - The template is now ng-template. You should use the “ng-
template” tag instead of “template”. Now Angular has its own template tag that is
called “ng-template”.

6. NgIf with Else – Now in Angular 4, possible to use an else syntax as,

<div *ngIf="user.length > 0; else empty"><h2>Users</h2></div>


<ng-template #empty><h2>No users.</h2></ng-template>

7. AS keyword – A new addition to the template syntax is the “as keyword” is use
to simplify to the “let” syntax.

Use of as keyword,
<div *ngFor="let user of users | slice:0:2 as total; index as = i">
{{i+1}}/{{total.length}}: {{user.name}}
</div>
To subscribe only once to a pipe “|” with “async” and If a user is an observable,
you can now use to write,

<div *ngIf="users | async as usersModel">


<h2>{{ usersModel.name }}</h2> <small>{{ usersModel.age }}</small>
</div>

8. Pipes - Angular 4 introduced a new “titlecase” pipe “|” and use to changes the
first letter of each word into the uppercase.

The example as,


<h2>{{ 'anil singh' | titlecase }}</h2>
<!-- OUPPUT - It will display 'Anil Singh' -->

9. Http - Adding search parameters to an “HTTP request” has been simplified as,

//Angular 4 -
http.get(`${baseUrl}/api/users`, { params: { sort: 'ascending' } });

//Angular 2-
const params = new URLSearchParams();
params.append('sort', 'ascending');
http.get(`${baseUrl}/api/users`, { search: params });

10. Test- Angular 4, overriding a template in a test has also been simplified as,

//Angular 4 -
TestBed.overrideTemplate(UsersComponent, '<h2>{{users.name}}</h2>');

//Angular 2 -
TestBed.overrideComponent(UsersComponent, {
set: { template: '<h2>{{users.name}}</h2>' }
});

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>`
})
export class UsersAppComponent {
constructor(meta: Meta) {
meta.addTag({ name: 'Blogger', content: 'Anil Singh' });
}
}

12. Forms Validators - One new validator joins the existing “required”,
“minLength”, “maxLength” and “pattern”. An email helps you validate that the
input is a valid email.

13. Compare Select Options - A new “compareWith” directive has been added
and it used to help you compare options from a select.

<select [compareWith]="byUId" [(ngModel)]="selectedUsers">


<option *ngFor="let user of users" [ngValue]="user.UId">{{user.name}}</option>
</select>

14. Router - A new interface “paramMap” and “queryParamMap” has been


added and it introduced to represent the parameters of a URL.

const uid = this.route.snapshot.paramMap.get('UId');


this.userService.get(uid).subscribe(user => this.name = name);

15. CanDeactivate - This “CanDeactivate” interface now has an extra (optional)


parameter and it is containing the next state.

16. I18n - The internationalization is tiny improvement.

//Angular 4-
<div [ngPlural]="value">
<ng-template ngPluralCase="0">there is nothing</ng-template>
<ng-template ngPluralCase="1">there is one</ng-template>
</div>

//Angular 2-
<div [ngPlural]="value">
<ng-template ngPluralCase="=0">there is nothing</ng-template>
<ng-template ngPluralCase="=1">there is one</ng-template>
</div>
What's New In Angular 5? [Angular 4 vs. Angular 5]
Anil Singh 4:19 AM Edit

Angular 5 is going to be a much better Angular and you will be able to


take advantage of it much easier and Version 5 will be fully released
on September/October 2017.

Stayed Informed – Angular 4 and Angular 2

The Angular 5 Contains bunch of new features, performance


improvements and lot of bug fixes and also some surprises to Angular
lovers.

1. Make AOT the default

2. Watch mode

3. Type checking in templates

4. More flexible metadata

5. Remove *.ngfactory.ts files

6. Better error messages

7. Smooth upgrades

8. Tree-Shakeable components

9. Hybrid Upgrade Application

10. And so on...

Angular 5 Performance Improvements - Angular 5


1. Use of addEventListener for the faster rendering and it is the core
functionality.

2. Update to new version of build-optimizer.

3. Added some Improvements on the abstract class methods and


interfaces

4. Remove decorator DSL which depends on Reflect for Improve the


Performance of Apps and This is the core functionality.

5. Added an option to remove blank text nodes from compiled templates

6. Switch Angular to use Static-Injector instead of Reflective-Injector.

7. Improve the applications testing.

8. Improve the performance of hybrid applications

9. Improvements on Lazy loading for Angular

10. And so on...

Some Improvement on HttpClient – This is used for Applications


communicate with backend services over the HTTP protocol!

1. Improvement on Type-checking the response

2. Improvement on Reading the full response

3. Improvement on Error handling and fetching error details

4. Improvement on Intercepting all requests or responses

5. Improvement on Logging

6. Improvement on Caching

7. Improvement on XSRF Protection


Added Features - Angular 5

1. Added Representation of Placeholders to xliff and xmb in the compiler

2. Added an Options Arg to Abstract Controls in the forms controls

3. Added add default updateOn values for groups and arrays to form
controls

4. Added updateOn blur option to form controls

5. Added updateOn submit option to form controls

6. Added an Events Tracking Activation of Individual Routes

7. Added NgTemplateOutlet API as stable in the common controls

8. Create StaticInjector which does not depend on Reflect polyfill

9. Added [@.disabled] attribute to disable animation children in the


animations

10. And so on..

Router Life Cycle Events – Angular 5

Added new router life cycle events for Guards and Resolvers -

1. GuardsCheckStart,

2. GuardsCheckEnd,

3. ResolveStart and

4. ResolveEnd

Angular 5 Bug Fixes - Angular 5

1. Fixed compilation error by using the correct type for providers


2. Skip PWA test when redeploying non-public commit

3. Don't strip CSS source maps. This is the compiler related fix

4. Remove tsickle (language-service) dependency

5. Support persisting dynamic styles within animation states

6. Ignore @import in multi-line css

7. Fix platform-browser-dynamic

8. Forbid destroyed views to be inserted or moved in VC

9. Support persisting dynamic styles within animation states

10. And so on...

What's New In Angular 6? What Are Improvements In


Angular 6?
Anil Singh 10:49 PM Edit

Off-course! Angular 6 being smaller, faster and easier to use and it will
making developers life easier. Recently Angular 6.0.0-beta.7 is released and
production release on end of March 2018.

The Angular Team are working on lots of bug fixes, new features and
added/update/remove/ re-introduce/ and may more things.

Let’s start to explore all changes of Angular 6 step by step!

Added ng update - This CLI commands will update your angular project
dependencies to their latest versions. The ng update is normal package manager
tools to identify and update other dependencies.

ng update
Angular 6 uses RxJS 6 - this is the third-party library (RxJS) and introduces two
important changes as compared to RxJS 5.
1. RxJS 6 introduces a new internal package structure
2. Operator concept

Both are requires you to update your existing code

To update to RxJS 6, you simply run -

npm install --save rxjs@6

Simply run the blow command and update your existing Angular project-

npm install --save rxjs-compat

Alternatively, you can use the command - ng update rxjs to update RxJS and install
the rxjs-compat package automatically.

RxJS 6 Related import paths -


Instead of -

import { Observable } from 'rxjs/Observable';

import { Subject } from 'rxjs/Subject';

Use a single import -

import { Observable, Subject } from 'rxjs';

So all from rxjs/Something imports become from one 'rxjs'


Operator imports have to change -
Instead of

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/throttle';

Now you can use -

import { map, throttle } from 'rxjs/operators';

And

Instead of

import 'rxjs/add/observable/of';

Now you can use -

import { of } from 'rxjs';

RxJS 6 Changes - Changed Operator Usage

Instead of-

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/throttle';

yourObservable.map(data => data * 2)

.throttle(...)

.subscribe(...);
You can use the new pipe () method,

import { map, throttle } from 'rxjs/operators';

yourObservable

.pipe(map(data => data * 2), throttle(...))

.subscribe(...);

CLI update and added a new project config file - Instead of “.angular-cli.json” using
“angular.json”
Now in Angular 6 new projects use an “angular.json” file instead of “.angular-
cli.json” file.

ng update @angular/cli --from=1 --migrate-only

The above command helps you to update your existing “.angular-cli.json” file to the
new “angular.json” file.

The “angular.json” file contains the Properties -


1. Version - This is integer file format version and it is currently 1.
2. newProjectRoot - This is string path where new projects will be created.
3. defaultProject - This is default project name used in commands.
4. CLI - This is workspace configuration options for Angular CLI and it contains
a. defaultCollection
b. packageManager
c. warnings
d. And so on.
5. Schematics - This is configuration options for Schematics.
6. Projects - This is configuration options for each project in the workspace and it
contains
a. root
b. sourceRoot
c. projectType
d. prefix
e. schematics

f. Architect - This is the project configuration for Architect targets.

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


Now in Angular 6, you should use <ng-template> instead of <template>

For example, previously you are using

<template [ngIf]="IsAdmin">

<p>This template renders only if IsAdmin is true.</p>

</template>

Now in Angular 6, you should use <ng-template> instead of <template>

<ng-template [ngIf]="IsAdmin">

<p>This template renders only if IsAdmin is true.</p>

</ng-template>

Service level changes (the way of marking a service as global) -


In the earlier versions, if you want to provide a service to the entire application –you
should add it to providers [] in the AppModule but in the Angular 6 released you
should not add in the providers [] in the AppModule.
Example for marking a service as global -

Instead of

//my.service.ts

export class MyService { }

//In app.module.ts

//JavaScript imports services

import { MyService } from './my-serice.service';

//AppModule class with the @NgModule decorator

@NgModule({

declarations: [],

providers: [MyService] //My services instances are now available across


the entire app.

})

export class AppModule {

//exporting app module

Use with Angular 6 released-

//my.service.ts

@Injectable({providedIn: 'root'})

export class MyService { }

@NgModule({

declarations: [],
providers: [] // Service does not need to be added here

})

export class AppModule {}

The second one obviously saves you some lines of code as compare to previous
code.

Angular 6 introduces Angular Elements -


The elements are a feature that allows you to compile Angular components to
native web components which you can use in your Angular application.

An angular element is a package which is part of the Angular framework


@angular/elements.

For more detail kindly refer the click to Angular Elements

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 production.

Ivy Renderer is new rendering engine which is designed to be backward compatible


with existing render and focused to improve the speed of rendering and it optimizes
the size of the final package.

The main goal of Ivy render is to speed up its loading time and reduce the bundle
size of your applications. Also for uses a different approach for rendering Angular
components.

For Angular, this will not be default renderer, but you can manually enable it in
compiler options.
Bazel Compiler -
The Bazel Complier is a build system used for nearly all software built at Google.

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.

The Bazel Complier uses advanced local and distributed caching, optimized
dependency analysis and parallel execution.

For more detail kindly refer the Angular 6

Replace Context, Record and Injectors -


Replace ngOutletContext with ngTemplateOutletContext
Replace CollectionChangeRecord with IterableChangeRecord
Now use Renderer2, Instead of Renderer

Now use StaticInjector, Instead of ReflectiveInjector,

Angular 6 Renamed Operators -


The lists of renamed operators are –
1. do() => tap()
2. catch() => catchError()
3. finally() => finalize()
4. switch() => switchAll()
5. throw() => throwError()
6. fromPromise() => from()

Angular 6 introduces multiple validators for array method of FormBuilder –

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

import {FormsModule, FormBuilder, FormGroup} from '@angular/forms';

constructor(private fb: FormBuilder) {}

myForm: FormGroup;

ngOnInit() {

this.myForm = this.fb.group({

text: ['', Validators.required],

options: this.fb.array([],
[MyValidators.minCount, MyValidators.maxCount])

});

Addition of navigationSource and restoredState to NavigationStart -

These two properties help us to handle multiple use cases in routing.

NgModelChange - Now emitted after value and validity is updated on its control.
Previously, it was emitted before updated.

As the updated value of the control is available, the handler will become more
powerful
Previously -

<input [(ngModel)]="name" (ngModelChange)="onChange($event)">

And

onChange(value) {

console.log(value); // would log the updated value, not old value

Now Use -

<input #modelDir="ngModel" [(ngModel)]="name" (ngModelChange)="onChange(


modelDir)">

And

onChange(NgModel: NgModel) {

console.log(NgModel.value);// would log old value, not updated value

Form Control statusChanges – Angular 6 emits an event of “PENDING” when we call


Abstract Control markAsPending.

New optional generic type ElementRef – This optional generic type will help to get
hold of the native element of given custom Element as ElementRef Type.

Angular 2 Components Example


Anil Singh 4:14 AM Edit

In Angular 2, the components are the main way to build or specify HTML elements and
business logic on the page.
In AngularJs 1, we are handling using scope, directives and controllers but all those concepts
are using in a single combined that is called components.

The component is the core functionality of Angular 2 app but we need to know to pass the
data in to the components to configure them.

Stayed Informed - Angular 2 Tutorials For Quick Start

To build an Angular 2 application you define a set of components, for every HTML elements,
views, and route.

Angular 2 applications must have a root component that contains all other components.
That means all Angular 2 applications have a component tree.

Application  Component  Component1 and Component2

Example of Components

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


import { CommonModule } from '@angular/common';

@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})

export class HomeComponent {


userlist: Users[];

constructor() {
this.userlist = [
{ Id: '1001', name: 'Anil Singh', site: 'http://www.code-sample.com' },
{ Id: '1002', name: 'Alok', site: 'http://www.code-view.com' },
{ Id: '1003', name: 'Reena', site: 'http://www.code-sample.xyz' },
{ Id: '1004', name: 'Dilip', site: 'http://www.codefari.com' },
];
}

values = '';
onKeyUp(event: any) {
this.values = event.target.value;
console.log(this.values);
};

onKeyDown(event: any) {
this.values = event.target.value;
console.log(this.values);
};
}

export class Users {


Id: String;
name: String;
site: String;
}

/* For HTML Components


<input type="text" [(value)]="values" (keyup)="onKeyUp($event)"
(keydown)="onKeydown($event)" />
*/

Angular 2 Component Summary

 Angular 2 Component meta-data annotation is used to register the components.

 Angular 2 components are used to create UI widgets.

 Angular 2 components are used to split to application into smaller parts.

 Only one component is used per DOM element.

 In the Angular 2 components, @View, template and templateUrl are mandatory in the
components.
Angular 2 components vs directives
Anil Singh 2:58 AM Edit

Angular 2 components vs directives

@Components @Directive

1. @Component meta-data annotation is @Directive meta-data annotation is


used to register the components. used to register the directives.

2. The components are used to create UI The directives are used to add behavior
widgets. to existing DOM elements.

3. The components are used to split to The directives are use to design a
application into smaller parts. reusable components.

4. Only one component is used per DOM More than one directive are used per
element. DOM element.

5. In the components, @View, template The directive do not have @View etc.
and templateUrl are mandatory in the
components.

Example for using Component.

import {Component, View} from 'angular2/core';

@Component({

selector: 'hello-world'

})

@View({

template: "<h1>Hello {{angular}}</h1>"

})
class hello {

constructor(public angular: string) {}

<hello-world></hello-world>

Example for using Directive.

import {Component, View} from 'angular2/core'';

@Component({

selector: 'user-detail'

})

@View({

template: "<div> <h1>{{userName}}</h1> <p>{{phone}}</p>"

})

class userDetail {

constructor(public userName: string, public phone: string) {}

<user-detail></user-detail>

Angular 2 Component Lifecycle Hooks [Examples Also]


Anil Singh 11:14 PM Edit
The common questions ask bye most of Angular 2 lovers,

“Could anyone tell me about the usage of ngOnInit if we


already have a constructor?” but Angular 2 provides life cycle hook
ngOnInit by default.

Angular 2 Components and Directives has multiple life-time hooks


where we custom logic can be executed.

Stayed Informed - What Are Components in Angular 5,4 and 2?

Angular 2 Constructors:-

The constructor is a default method runs when component is being


constructed.

The constructor is a typescript feature and it is used only for a class


instantiations and nothing to do with Angular 2.

The constructor called first time before the ngOnInit().


Example as,
import {Component} from 'angular2/core';
import {UserService} from './userService';

@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:-

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
parameters defined with @Input otherwise the constructor is OK.

The ngOnInit is called after the constructor and ngOnInit is called after
the first ngOnChanges.

The ngOnChanges is called when an input or output binding value


changes.
Examples as,
import {Component, OnInit} from '@angular/core';
export class App implements OnInit{
constructor(){
}

ngOnInit(){
}
}

Angular 2 ngOnDestroy :-

The ngDestroy directive is called in a component lifecycle just before


the instance of the component is finally destroyed.

Example as,
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {

//Call Constructor and set hello Msg.


constructor() {
this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
}

//Destroy to the component


ngOnDestroy() {
window.clearInterval(this.helloMsg);
}
}

Angular 2 Complete lifecycle hook interface inventory:-


1. ngOnChanges - called when an input binding value changes.

2. ngOnInit - after the first ngOnChanges.

3. ngDoCheck - after every run of change detection.

4. ngAfterContentInit - after component content initialized.

5. ngAfterContentChecked - after every check of component content.

6. ngAfterViewInit - after component's view(s) are initialized.

7. ngAfterViewChecked - after every check of a component's view(s).

8. ngOnDestroy - just before the component is destroyed.

Angular 2 Lifecycle Events Log:-


1. onChanges

2. onInit

3. doCheck

4. afterContentInit

5. afterContentChecked

6. afterViewInit
7. afterViewChecked

8. doCheck

9. afterContentChecked

10. afterViewChecked

11. onChanges

12. doCheck

13. afterContentChecked

14. afterViewChecked

15. onDestroy

Angular 2 @Inputs - How to Passing data into Angular 2


components with @Input?
Anil Singh 1:29 AM Edit

@Input allows you to pass data into your controller and templates through html
and defining custom properties.

@Input is used to define an input for a component, we use the @Input decorator.

Angular 2 components is the core components of applications but you must need to
know “how to pass data into components to dynamically?” and that time you
need to define an input component.

Stayed Informed - Angular 2 @Output


You can see the below example for passing the user data in to the components.

Example 1,
import { Component, Input } from '@angular/core';

@Component({
selector: “user-info”,
template: “<div> Hello, This is {{ userInfo.name}}</div>”
})
export class UserInfo {
@Input() userInfo;
constructor() { }
}

<user-info [userInfo]="currentUser"></user-info>

The components <user-info></user-info> is use to render the user information


on the view.

Example 2,

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

@Component({
selector: 'app-root',
styles: [`
.app {
text-align: center;
background: #f5f5f5;
}
`],
template: `
<div class="app">
<counter [count]="defaultCount"></counter>
</div>
`
})
export class AppComponent {
defaultCount: number = 20;

Angular 2 Component Outputs [@Output Property]


Anil Singh 5:01 AM Edit

@Output decorator is used to binds a property of a component to send the data


from child component to parent component and this is a one-way communication.

@Output decorates output properties and its binds a property of the type of
angular EventEmitter.
Stayed Informed - Angular 2 @Inputs

Stayed Informed - Angular 4 vs. Angular 2

If you want to bind an event on an element, you can use the


new Angular2 events i.e.

@Component(...)
class yourComponent {
addUser(event) {
}
}

The method addUser() will be called when user clicked on button.

<button (click)="addUser()">Click</button>

<button (click)="addUser($event)"></button>

What happen if you want to create a custom event?

Now come to the outputs, if you want to create your custom event in Angular 2 that
time we will use to new @Outputdecorator.

Examples,
import { Component} from 'angular2/core';
import { bootstrap} from 'angular2/platform/browser';

@Component({
selector: 'my-app',
providers: [Service],
template: '<div>Hello my name is {{name}}!</div>'
})
class MyApp {
constructor(service: Service) {
this.name = service.getName();
setTimeout(() => this.name = 'Anil Singh,', 1000);
}
}
class Service {
getName() {
return 'Hello';
}
}

bootstrap(App);

In the above example, we will need to import Output and Event-Emitter to


create our new custom event.

import { Component , Output, EventEmitter} from 'angular2/core';


import { bootstrap} from 'angular2/platform/browser';

@Component({
selector: 'my-app',
providers: [Service],
template: '<div>Hello my name is {{name}}!</div>'
})
class MyApp {
constructor(service: Service) {
this.userClicked.emit(this.user);

this.name = service.getName();

setTimeout(() => this.name = 'Anil Singh,', 1000);


}
}
class Service {
getName() {
return 'Hello';
}
@Output() userClicked = new EventEmitter();
}
bootstrap(App);

Angular 2 Hidden Attribute with Multiple Examples


Anil Singh 11:30 PM Edit

Angular 2 [hidden] is a special case binding to hidden property.

It is closest cousin of ng-show and ng-hide.


It is more powerful to bind any property of elements. Both the ng-show and ng-hide
are used to manage the visibility of elements using ng-hide css class. It is also set
the display property “display:none”.

Stayed Informed - Angular 2 @Inputs


All the above features are supported in Angular 2 but added some extra feature like
animations etc.

Syntax:-
<div [hidden]="!active">
Hello, this is active area!
</div>

Note: - Don't use hidden attribute with Angular 2 to show/hide elements.

Question: - Don't use hidden attribute with Angular 2. Here is why?

The hidden attribute is used to hide elements. Browsers are not supposed to display
elements that have the hidden attribute specified. Browsers attach "display: none"
styles to elements with hidden attribute.

Example,
import { Component } from 'angular2/core';

@Component({
selector: 'demo',
templateUrl: 'app/component.html'
})
export class MainComponent {
Ishide: true;
}
<div [hidden]="Ishide">
Hey, I’m using hidden attribute.
</div>

Works great but some time its override hidden attribute with some css and that
time behave wrong!..

For example,

Be sure to don't have a display css rule on your <p> tags who override hidden
behaviour like i.e.

p{
display: inline-block !important;
}

The above hidden html attributes acts like display: none;

How do Components Communicate with Each Other in


Angular 2?
Anil Singh 10:44 PM Edit

In Angular 1, I have some ways to communicate between controllers i.e.

1. $rootScope,

2. $scope,

3. $emit,

4. $broadcast

Now In Angular 2, we have different ways to communicate between components.


A parent component and its children share a service whose interface enables bi-
directional communication within the family.

Stayed Informed - Angular2 Components Life-cycle

The following examples for Services communication,


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

@Injectable()
export class MyService {
constructor() { }
}

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

@Component({
selector: 'my-app',
templateUrl: './myApp.component.html'
})
export class MyAppComponent { }

The following example to calling service from any other component,


import {Component, OnInit} from '@angular/core';
import {MyService} from './app/myService';

@Component({
selector: '<my-component></my-component>',
templateUrl: 'app/component.html',
providers: [MyService]
})

export class MyComponent implements OnInit {


constructor(private msInstance: MyService) {}
ngOnInit() {
this.msInstance.getServices();
}
}
Example for Sibling Component Communication,

import { Component, ViewChild, AfterViewInit } from '@angular/core';


import { ListComponent } from './list.component';
import { DetailComponent } from './detail.component';

@Component({
selector: 'app-component',
template: '<list-component></list-component><detail-component></detail-component>',
directives: [ListComponent, DetailComponent]
})
class AppComponent implements AfterViewInit {
@ViewChild(ListComponent) listComponent:ListComponent;
@ViewChild(DetailComponent) detailComponent: DetailComponent;

ngAfterViewInit() {
// afther this point the children are set, so you can use them
this.detailComponent.doSomething();
}
}
How do we display errors in a component view with
Angular 2?
Anil Singh 11:20 PM Edit

How To Display Validation and Error Messaging on form submit in Angular 2?

In Angular 1, the ng-messages modules are used to help us to display error


messages and validation to our forms.

In Angular 2, the ngModel provides error objects for each of the built-in input
validators. You can access these errors from a reference to the ngModel itself then
build useful messaging around them to display to your users.

Stayed Informed - Angular2 email forms validation


And also, we can use the properties “pristine” and “touched” to display error
messages.

1. If we want to display errors after the user fills something in a field, use the pristine
property.

2. If we want to display errors after the user put the focus on a field, use the touched
property.

Example as,
<div *ngIf="(!loginForm.controls.email.valid && !loginForm.controls.email.pristine)">
**Email is required.
</div>

ElementRef vs Renderer - Angular 2


Anil Singh 10:20 PM Edit

What are the difference between Renderer and ElementRef in angular 2?

ElementRef vs. Renderer -

In Angular Renderer and ElementRef are used for DOM Manipulation and Renderer
and ElementRef are used together to get full platform abstraction.

Renderer –
Renderer is a class that is a partial abstraction done the DOM manipulations and the
DOM manipulating is not breaking server side rendering or web workers.

ElementRef –

ElementRef is a class that is a partial abstraction done the DOM Manipulations


without breakable environments and it also can hold a reference to a DOM
elements.

If “ElementRef” is injected to a component, the injected instance is a reference to


the host element of the current component.

The ways to get an ElementRef instance looks like,

1. @ViewChild()

2. @ViewChildren()

3. @ContentChild()

4. @ContentChildren()

In this case the ElementRef is a reference to the matching elements in the


templates.

Do notice that you should refrain from using ElementHref as it flagged


with a security risk?
If you allow direct access to the DOM, it can make your application more vulnerable
to XSS attacks. So make sure, when you are using to ElementRef in your app code.

What is the point of calling renderer.invokeElementMethod(rendererEl,


methodName)?

//our root app component


import {Component, ElementRef} from 'angular2/core'
import * as browser from 'angular2/platform/browser'
import {Ruler, Rectangle} from 'angular2/src/platform/browser/ruler.js'

@Component({
selector: 'my-app',
providers: [ElementRef],
template: `
<div>
<h2>Hello {{name}}</h2>
<p>H2 Height: {{rect.height}}</p>
<p>H2 Width: {{rect.width}}</p>
</div>
`,
directives: []
})
export class App {
constructor(element: ElementRef) {
this.name = 'Angular2'
this.element = element;
this.ruler = new Ruler(new browser.BrowserDomAdapter());
this.rect = {};
}
ngOnInit() {
var vm = this;
var measure = this.ruler.measure(this.element);
measure.then(function (rect) {
console.log('Rect', rect);
vm.rect = rect;
});
}
}

What is Angular 2 Service? [Steps For Create and Use of


Angular 2 Services]
Anil Singh 3:36 AM Edit
What is an Angular 2 Service?

Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and


provides it result as a service for across your application.

What are the features of Angular 2 Service?

The Angular 2 is using services concept and it provide the multiple features to us
that are,

1. Services are singleton objects.

2. Services are capable of returning the data in the form promises or observables.

3. Service class is decorated with Injectable decorator.

4. The Injectable decorator is required only if our service class is making use of some
Angular injectable like Http, Response and HttpModule service within it.

What are the differences between Observables & Promises?

1. Promise:- Promises are only called once and It can return only a single value at a
time and the Promises are not cancellable.

2. Observables:- Observables handle multiple values over time and it can return
multiple values and the Observables are cancellable.

3. The Observables are more advanced than Promises.

Steps for creating an Angular 2 Service:-

There are four steps as,

1. Import the injectable member i.e.

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


2. Import the HttpModule, Http and Response members’ i.e.

import { HttpModule, Http, Response } from '@angular/http';

3. Add the @Injectable Decorator i.e. @Injectable()


4. Export to the Service class i.e.

export class UserService {


constructor(private _http: Http) { }

Steps for Calling an Angular 2 Service in the Angular 2 Component class:-

There are four steps to calling a service in component as,

1. Create or Import the Service to the component class.

2. Add it as a component provider.

3. Include it through Dependency Injection.

4. Use the Service function in the component.

In the below Example,

I hope this will help you to understand and create the basic of Angular 2 service. I
am creating a user service and this user service returns the list of users.

After creating user service, I will use the user service “getUsers()” method in the
user component’s ngOnInit() method to load the returns user collections on user
screen.
I am also using the REST API Url (https://api.github.com/users/hadley/orgs) and this
RESTful API will returns the users.

app.module.ts :-

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

import { RouterModule, Routes } from '@angular/router';

import { UniversalModule } from 'angular2-universal';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { AppComponent } from './components/app/app.component';

import { UserComponent } from './components/user/user.component';

import { HeaderComponent } from './components/shared/header/header.component';

import { MenuComponent } from './components/menu/menu.component';

import { LoginComponent } from './components/login/login.component';

import { RegistrationComponent } fro


m './components/registration/registration.component';

@NgModule({

bootstrap: [ AppComponent ],

declarations: [

AppComponent,

UserComponent,

HeaderComponent,

MenuComponent,

LoginComponent,

RegistrationComponent
],

imports: [

UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS


BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.

RouterModule.forRoot([ //RouterModule.forRoot method in the module


imports to configure the router.

{ path: '', redirectTo: 'user', pathMatch: 'full' },

{ path: 'user/:id', component: UserComponent }, //HERE ID IS A ROUTE


PARAMETER.

{ path: 'login', component: LoginComponent },

{ path: 'registration', component: RegistrationComponent },

{ path: '**', redirectTo: 'user' }

]),

FormsModule,

ReactiveFormsModule

})

export class AppModule {

user.component.ts and user.service.ts :-

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

import { CommonModule } from '@angular/common';

import { HttpModule, Http, Response } from '@angular/http';

//BEGIN-REGION - USERSERVICE

@Injectable()

export class UserService {

constructor(private _http: Http) { }

getUsers(apiUrl) {
return this._http.get(apiUrl).map((data: Response) => data.json());

//END BEGIN - USERSERVICE

//BEGIN-REGION - USERCOMPONENT

@Component({

selector: 'user',

templateUrl: './user.component.html',

styleUrls: ['./user.component.css'],

providers: [UserService]

})

export class UserComponent {

//USERS DECLARATIONS.

users = [];

//FETCHING JSON DATA FROM REST APIS

userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

//HOME COMPONENT CONSTRUCTOR

constructor(private userService: UserService) { }

//GET USERS SERVICE ON PAGE LOAD.

ngOnInit() {

this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);

//END BEGIN – USERCOMPONENT

user.component.html :-
<div class="row">

<div class="col-lg-12">

<div class="ibox float-e-margins">

<div class="ibox-title">

<h2>Angular 2 - User Services</h2>

</div>

<hr />

<div class="ibox-content">

<div class="table-responsive">

<table class="table table-striped">

<thead>

<tr>

<th>ID</th>

<th>Name </th>

<th>Description </th>

<th>URls </th>

</tr>

</thead>

<tbody>

<tr *ngFor="let user of users; let i = index">

<td>{{user.id}}</td>

<td>{{user.login}}</td>

<td>{{user.description}}</td>

<td><a href="{{user.public_members_url}}"> {{user.pub


lic_members_url}}</a></td>

</tr>

</tbody>

</table>

</div>

</div>

</div>
</div>

</div>

Angular 2 http Service Requests with Example


Anil Singh 4:33 AM Edit

Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and


provides it result as a service for across your application.

The Angular 2 is using services concept and it provide the multiple features to us
that are,

1. Services are singleton objects.

2. Services are capable of returning the data in the form promises or observables.

3. Service class is decorated with Injectable decorator.

4. The Injectable decorator is required only if our service class is making use of some
Angular injectable like Http, Response and HttpModule service within it.

Stayed Informed –Angular 2 Tutorials and Examples

Steps for creating an Angular 2 Service:-

There are four steps as,

1. Import the injectable member i.e.

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

2. Import the HttpModule, Http and Response members’ i.e.

import { HttpModule, Http, Response } from '@angular/http';

3. Add the @Injectable Decorator i.e. @Injectable()


4. Export to the Service class i.e.

export class UserService {


constructor(private _http: Http) { }

Steps for Calling an Angular 2 Service in the Angular 2 Component class:-

There are four steps to calling a service in component as,

1. Create or Import the Service to the component class.

2. Add it as a component provider.

3. Include it through Dependency Injection.

4. Use the Service function in the component.

In the below Example,

I hope this will help you to understand and create the basic of Angular 2 service. I
am creating a user service and this user service returns the list of users.

After creating user service, I will use the user service “getUsers()” method in the
user component’s ngOnInit() method to load the returns user collections on user
screen.

I am also using the REST API Url (https://api.github.com/users/hadley/orgs) and this


RESTful API will returns the users.
app.module.ts :-
import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { UniversalModule } from 'angular2-universal';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { AppComponent } from './components/app/app.component';

import { UserComponent } from './components/user/user.component';

import { HeaderComponent } from './components/shared/header/header.component';

import { MenuComponent } from './components/menu/menu.component';

import { LoginComponent } from './components/login/login.component';

import { RegistrationComponent } fro


m './components/registration/registration.component';

import { UserService } from './components/app/user.service';

@NgModule({

bootstrap: [ AppComponent ],

declarations: [

AppComponent,

UserComponent,

HeaderComponent,

MenuComponent,

LoginComponent,

RegistrationComponent

],

imports: [

UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS


BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.

RouterModule.forRoot([ //RouterModule.forRoot method in the module


imports to configure the router.

{ path: '', redirectTo: 'user', pathMatch: 'full' },


{ path: 'user/:id', component: UserComponent }, //HERE ID IS A ROUTE
PARAMETER.

{ path: 'login', component: LoginComponent },

{ path: 'registration', component: RegistrationComponent },

{ path: '**', redirectTo: 'user' }

]),

FormsModule,

ReactiveFormsModule

],

providers: [UserService]

})

export class AppModule {

user.service.ts :-
import { Injectable } from '@angular/core';

import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

//BEGIN-REGION - USERSERVICE

@Injectable()

export class UserService {

constructor(private _http: Http) {

getUsers(apiUrl) {

return this._http.get(apiUrl).map((data: Response) => data.json());

//END BEGIN - USERSERVICE


user.component.ts:-
import { Component, Injectable} from '@angular/core';

import { CommonModule } from '@angular/common';

import { UserService } from './components/app/user.service';

//BEGIN-REGION - USERCOMPONENT

@Component({

selector: 'user',

templateUrl: './user.component.html',

styleUrls: ['./user.component.css'],

providers: [UserService]

})

export class UserComponent {

//USERS DECLARATIONS.

users = [];

//FETCHING JSON DATA FROM REST APIS

userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

//HOME COMPONENT CONSTRUCTOR

constructor(private userService: UserService) { }

//GET USERS SERVICE ON PAGE LOAD.

ngOnInit() {

this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);

//END BEGIN – USERCOMPONENT


user.component.html :-
<div class="row">

<div class="col-lg-12">

<div class="ibox float-e-margins">

<div class="ibox-title">

<h2>Angular 2 - User Services</h2>

</div>

<hr />

<div class="ibox-content">

<div class="table-responsive">

<table class="table table-striped">

<thead>

<tr>

<th>ID</th>

<th>Name </th>

<th>Description </th>

<th>URls </th>

</tr>

</thead>

<tbody>

<tr *ngFor="let user of users; let i = index">

<td>{{user.id}}</td>

<td>{{user.login}}</td>

<td>{{user.description}}</td>

<td><a href="{{user.public_members_url}}"> {{user.pub


lic_members_url}}</a></td>

</tr>

</tbody>

</table>

</div>

</div>

</div>

</div>
</div>

Result :-

How To Create a Singleton Service in Angular 2?


Anil Singh 3:54 AM Edit

What is an Angular 2 Service?

Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and


provides it result as a service for across your application.

What are the features of Angular 2 Service?

The Angular 2 is using services concept and it provide the multiple features to us
that are,

1. Services are singleton objects.

2. Services are capable of returning the data in the form promises or observables.

3. Service class is decorated with Injectable decorator.

4. The Injectable decorator is required only if our service class is making use of some
Angular injectable like Http, Response and HttpModule service within it.

Stayed Informed –Angular 2 Tutorials and Examples

Steps for creating an Angular 2 Service:-

There are four steps as,

1. Import the injectable member i.e.

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


2. Import the HttpModule, Http and Response members’ i.e.

import { HttpModule, Http, Response } from '@angular/http';

3. Add the @Injectable Decorator i.e. @Injectable()


4. Export to the Service class i.e.

export class UserService {


constructor(private _http: Http) { }

Steps for Calling an Angular 2 Service in the Angular 2 Component class:-

There are four steps to calling a service in component as,

1. Create or Import the Service to the component class.

2. Add it as a component provider.

3. Include it through Dependency Injection.

4. Use the Service function in the component.

In the below Example,

I hope this will help you to understand and create the basic of Angular 2 service. I
am creating a user service and this user service returns the list of users.
After creating user service, I will use the user service “getUsers()” method in the
user component’s ngOnInit() method to load the returns user collections on user
screen.

I am also using the REST API Url (https://api.github.com/users/hadley/orgs) and this


RESTful API will returns the users.

app.module.ts :-
import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { UniversalModule } from 'angular2-universal';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { AppComponent } from './components/app/app.component';

import { UserComponent } from './components/user/user.component';

import { HeaderComponent } from './components/shared/header/header.component';

import { MenuComponent } from './components/menu/menu.component';

import { LoginComponent } from './components/login/login.component';

import { RegistrationComponent } fro


m './components/registration/registration.component';

@NgModule({

bootstrap: [ AppComponent ],

declarations: [

AppComponent,

UserComponent,

HeaderComponent,

MenuComponent,

LoginComponent,
RegistrationComponent

],

imports: [

UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS


BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.

RouterModule.forRoot([ //RouterModule.forRoot method in the module


imports to configure the router.

{ path: '', redirectTo: 'user', pathMatch: 'full' },

{ path: 'user/:id', component: UserComponent }, //HERE ID IS A ROUTE


PARAMETER.

{ path: 'login', component: LoginComponent },

{ path: 'registration', component: RegistrationComponent },

{ path: '**', redirectTo: 'user' }

]),

FormsModule,

ReactiveFormsModule

})

export class AppModule {

user.component.ts and user.service.ts :-


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

import { CommonModule } from '@angular/common';

import { HttpModule, Http, Response } from '@angular/http';

//BEGIN-REGION - USERSERVICE

@Injectable()

export class UserService {

constructor(private _http: Http) { }

getUsers(apiUrl) {

return this._http.get(apiUrl).map((data: Response) => data.json());


}

//END BEGIN - USERSERVICE

//BEGIN-REGION - USERCOMPONENT

@Component({

selector: 'user',

templateUrl: './user.component.html',

styleUrls: ['./user.component.css'],

providers: [UserService]

})

export class UserComponent {

//USERS DECLARATIONS.

users = [];

//FETCHING JSON DATA FROM REST APIS

userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

//HOME COMPONENT CONSTRUCTOR

constructor(private userService: UserService) { }

//GET USERS SERVICE ON PAGE LOAD.

ngOnInit() {

this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);

//END BEGIN – USERCOMPONENT

user.component.html :-
<div class="row">
<div class="col-lg-12">

<div class="ibox float-e-margins">

<div class="ibox-title">

<h2>Angular 2 - User Services</h2>

</div>

<hr />

<div class="ibox-content">

<div class="table-responsive">

<table class="table table-striped">

<thead>

<tr>

<th>ID</th>

<th>Name </th>

<th>Description </th>

<th>URls </th>

</tr>

</thead>

<tbody>

<tr *ngFor="let user of users; let i = index">

<td>{{user.id}}</td>

<td>{{user.login}}</td>

<td>{{user.description}}</td>

<td><a href="{{user.public_members_url}}"> {{user.pub


lic_members_url}}</a></td>

</tr>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>
Result :-

Angular 2 Pipes in Depth [Custom Pipes and Inbuilt Pipes


with Examples]
Anil Singh 11:02 PM Edit

This post helps us to learn “Angular 2 Pipes in Depth” and we will cover most of all
questions and answers related to the pipes.

1. What is Pipes?

2. Why use Pipes?

3. What is a pure and impure pipe?

4. What is Async Pipe?

5. How to create and use a custom pipe?

6. How to create a globally available custom“Pipe”?

What is Pipes?

“Pipes transform displayed values within a template.”

Sometimes, the data is not displays in the well format on the template that time
where using pipes.

You also can execute a function in the template to get its returned value.
The angular 2 have some additional pipes names that are async, decimal, percept
and so on. And also some of pipes not supported in angular 2 that are number,
orderBy and filter and these are archiving using “custom pipes”.

Key Points:-

Pipe class implements the “PipeTransform” interfaces transform method that


accepts an input value and returns the transformed result.

There will be one additional argument to the transform method for each parameter
passed to the pipe.

The “@Pipe” decorator allows us to define the pipe name that is globally available
for use in any template in the across application.

For example as,


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'barcode',
pure: false
})
export class BarCodePipe implements PipeTransform {
transform(value: string, args: any[]): string {
if (!value) {
return '';
}
return "****-****_" + (value.length > 8 ? (value.length - 8): '')
}

Angular 2 Built-in Pipes:-

1. DatePipe,

2. UpperCasePipe,

3. LowerCasePipe,

4. CurrencyPipe,

5. PercentPipe,

6. JsonPipe,

7. AsyncPipe,

8. And so on..

The following table shows a comparison between Angular 1.x and Angular 2.
Why use Pipes?

Sometimes, the data is not displays in the correct format on the template that time
where using pipes.

You also can execute a function in the template to get its returned value.

For example as,

If you want to display the bank card number on your account detail templates that
how to displays this card number? I think you should display the last four digits and
rest of all digits will display as encrypted like (****-****-****_and your card
numbers) that time you will need to create a custom pipe to achieve this.
What is a pure and impure pipe?

In Angular 2, there are two types of pipes i.e.

1. pure

2. impure

The pure pipe is by default. Every pipe has been pure by default. If you want to
make a pipe impure that time you will allow the setting pure flag to false.

Pure Pipes:-

Angular executes a pure pipe only when it detects a pure change to the input value.
A pure change can be primitive or non-primitive.

Primitive data are only single values, they have not special capabilities and the non-
primitive data types are used to store the group of values.
For example for pipe pure,
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'barcode'
})
export class BarCodePipe implements PipeTransform {
transform(value: string, args: any[]): string {
if (!value) {
return '';
}
return "****-****_" + (value.length > 8 ? (value.length - 8): '')
}

Impure Pipes:-

Angular executes an impure pipe during every component change detection cycle.
An impure pipe is called often, as often as every keystroke or mouse-move. If you
want to make a pipe impure that time you will allow the setting pure flag to false.

For example for pipe impure,


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'barcode',
pure: false
})
export class BarCodePipe implements PipeTransform {
transform(value: string, args: any[]): string {
if (!value) {
return '';
}
return "****-****_" + (value.length > 8 ? (value.length - 8): '')
}

What is Async Pipe?

Angular 2 provides us special kinds of pipe that is called Async pipe and the Async
pipe subscribes to an Observable or Promise and returns the latest value it has
emitted.

The Async pipe allows us to bind our templates directly to values that arrive
asynchronously manner and this is the great ability for the promises and
observables.

Example for AsyncPipe with Promise using NgFor,

@Component({
selector: 'app-promise',
template: '<ul> < li * ngFor="let user of users | async"> Id: {{user.id }}, Name:
{{user.name }} </li>< /ul>'
})
export class PromiseComponent {
//USERS DECLARATIONS.
users = [];

//FETCHING JSON DATA FROM REST APIS


userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

//HOME COMPONENT CONSTRUCTOR


constructor(private userService: UserService) { }

//GET USERS SERVICE ON PAGE LOAD.


ngOnInit() {
this.userService.getUsers(this.userRestApiUrl).subscribe(data => this.users =
data);
}

How to create a custom Pipes?

How to create a globally available custom “Pipe”?

The “@Pipe” decorator allows us to define the pipe name that is globally available
for use in any template in the across application.
Steps for Creating a Custom Pipe:-

1. Create a typescript class.

2. Decorate the class using @Pipe.

3. Implement PipeTransform interface.

4. Override transform() method.

5. Configure the class in application module with @NgModule.

6. Ready to use our custom pipe anywhere in application.

In the below example,

I am using the custom pipe in the user temple to display our custom “Ids” values at
the place of Id.

Table of Component

1. user.component.ts

2. user.service.ts

3. custom.barcode.pipe.ts

4. app.module.ts

5. user.component.html

user.component.ts :-
import { Component, Injectable} from '@angular/core';

import { CommonModule } from '@angular/common';

import { HttpModule, Http } from '@angular/http';

import { UserService } from '../shared/service/user.service';

import { BarCodePipe } from '../shared/pipe/custom.barcode.pipe';

@Component({

selector: 'user',

templateUrl: './user.component.html',

styleUrls: ['./user.component.css']

})

export class UserComponent {

//USERS DECLARATIONS.

users = [];

//FETCHING JSON DATA FROM REST APIS

userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

//HOME COMPONENT CONSTRUCTOR

constructor(private userService: UserService) { }

//GET USERS SERVICE ON PAGE LOAD.

ngOnInit() {

this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);

//END BEGIN - USERCOMPONENT

user.service.ts :-
import { Injectable } from '@angular/core';

import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';

//BEGIN-REGION - USERSERVICE

@Injectable()

export class UserService {

constructor(private _http: Http) {

getUsers(apiUrl) {

return this._http.get(apiUrl).map((data: Response) => data.json());

//END BEGIN – USERSERVICE

custom.barcode.pipe.ts :-

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({

name: 'barcode',

pure: false

})

export class BarCodePipe implements PipeTransform {

transform(value: string, args: any[]): string {

if (!value) {

return '';
}

return "....-" + (value.length > 2 ? (value.length - 2) : '')

app.module.ts :-

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

import { RouterModule, Routes } from '@angular/router';

import { UniversalModule } from 'angular2-universal';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { AppComponent } from './components/app/app.component';

import { UserComponent } from './components/user/user.component';

import { HeaderComponent } from './components/shared/header/header.component';

import { MenuComponent } from './components/menu/menu.component';

import { LoginComponent } from './components/login/login.component';

import { RegistrationComponent } fro


m './components/registration/registration.component';

import { UserService } from './components/shared/service/user.service';

import { BarCodePipe } from './components/shared/pipe/custom.barcode.pipe';

import { MyPipePipe } from './components/shared/pipe/test.pipes';

@NgModule({

bootstrap: [ AppComponent ],

declarations: [

AppComponent,

UserComponent,

HeaderComponent,

MenuComponent,
LoginComponent,

RegistrationComponent,

BarCodePipe,

MyPipePipe

],

imports: [

UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS


BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.

RouterModule.forRoot([ //RouterModule.forRoot method in the module


imports to configure the router.

{ path: '', redirectTo: 'user', pathMatch: 'full' },

{ path: 'user/:id', component: UserComponent }, //HERE ID IS A ROUTE


PARAMETER.

{ path: 'login', component: LoginComponent },

{ path: 'registration', component: RegistrationComponent },

{ path: '**', redirectTo: 'user' }

]),

FormsModule,

ReactiveFormsModule

],

providers: [UserService]

})

export class AppModule {

user.component.html :-

<div class="row">

<div class="col-lg-12">

<div class="ibox float-e-margins">

<div class="ibox-title">

<h2>Angular 2 - User Services</h2>


</div>

<hr />

<div class="ibox-content">

<div class="table-responsive">

<table class="table table-striped">

<thead>

<tr>

<th>ID</th>

<th>Name </th>

<th>Description </th>

<th>URls </th>

</tr>

</thead>

<tbody>

<tr *ngFor="let user of users; let i = index" class="tbl-


row-border">

<td>{{user.id | barcode: true}}</td>

<td>{{user.login}}</td>

<td>{{user.description}}</td>

<td><a href="{{user.public_members_url}}" target="_bl


ank">{{user.public_members_url}}</a></td>

</tr>

</tbody>

</table>

</div>

</div>

</div>

</div>

</div>

Result –
Angular 2 Directives [Components, Structural, Attribute
Directives]
Anil Singh 12:00 AM Edit

There are 3 types of directives in Angular 2.


1. Components Directives - directives with a template
2. Structural Directives - change the DOM layout by adding and
removing DOM elements.
3. Attribute Directives - change the appearance or behavior of an
element, component, or other directive.

Stayed Informed – Angular 2 Components Lifecycle Hooks

Stayed Informed – KendoUI for Angular 2 Grids

What are components directives?


A component is a directive with a template and the @Component
decorator is actually a @Directive decorator extended with
template oriented features.

1. To register a component, we use @Component meta-data


annotation.
2. The directives are used to add behavior to existing DOM
elements.
3. The directives are used to design a reusable component.
4. Only one component can be present per DOM element.
5. Multiple directives are used per DOM element.
6. The directive does not have @View etc.

What are structural directives?


The Structural directives are responsible for HTML layout and It is
using Angular 2 for reshape the DOM's structure and also
removing, or manipulating elements.

What are attribute directives?


Attribute directives are used to change the behavior, appearance
or look of an element on a user input or via data from the service.

For example as,


import {Component, View} from 'angular2/core'';

@Component({
selector: 'user-detail'
})

@View({
template: "<div> <h1>{{userName}}</h1> <p>{{phone}}</p>"
})

class userDetail {
constructor(public userName: string, public phone: string) {}
}

<user-detail></user-detail>
Angular 2 Templates - template vs. templateUrl? How to
Use Inline and External Templates?
Anil Singh 12:28 AM Edit

A template is a HTML view that tells Angular 2 for render your components in the
views.

The Angular 2 templates are very similar to Angular 1 but Angular 2 has some small
syntactical changes.

You can see the changes as below,

1. {}: Is use to rendering the HTML elements.

2. []: Is use to binding properties.

3. (): Is use to handling your events.

4. [()]: Is use to data binding.

5. *: Is use to asterisk Operations like *ngFor="let item of items; let i=index;”

The templates can be inline or external separate files.

Stayed Informed - Bindings in Angular 2

How to use {}, [], [] and [()] in Angular2 Template?

Here, I am using “Inline Template” in the user components i.e.


import { Component } from '@angular/core';
@Component({
selector: 'Users',
template: `<div>
<input (keyup)="onKey($event)" (click)="onClick()"/>
<div [hidden]="isActive" class="info">
<h2>Active element or Not?</h2>
<div>{{values}}</div>
</div>
</div>`,
styleUrls: ['./user.component.css']
})

export class UsersComponent {


values: string;
isActive: boolean = false;

onKey(event) {
this.isActive = true;
this.values += event.target.value;
}
}

What are differences of using template and templateUrl in Angular 2


Component?

Angular 2 template vs. templateUrl?

When using template vs. templateUrl?

Inline templates are specified directly in the component using template and it is
more complex for bigger templates. As per expert suggestions, use templates and
styles into a separate file, when your code more than 5 to 10 lines.

External templates define the HTML in a separate file and reference this file in
templateUrl.
To use a relative path in the templateUrl we must include import component form
@angular/core

Some befits for template Urls i.e.

1. Separations of code

2. Easy debugging

The upcoming offline template compiler will inline templates linked by templateUrl.

Example for Inline Template -


import { Component } 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: 'users-app',
template: `<div *ngFor="let user of users; let i = index">
<div>{{user.id }}</div>
<div>{{user.id | barcodepipe:true}}</div>
<div>{{user.login}}</div>
<div>{{user.description}}</div>
<div><a href="{{user.public_members_url}}"
target="_blank">{{user.public_members_url}}</a></div>
</div>`,
styleUrls: ['./user.component.css'],
providers: [UserService, AppGlobals],
})
export class UsersApp {
//USERS DECLARATIONS.
users = [];

//USER COMPONENT CONSTRUCTOR.


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

//GET USERS SERVICE ON PAGE LOAD and BIND UI GRID.


ngOnInit() {
this._userService.getAPIUsers(this._global.baseAPIUrl +
'users/api/GetUsers').subscribe(data => this.users = data);
}
}

Example for external templates - Separate file-


import { Component} 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: 'users-app',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService, AppGlobals],
})
export class UsersApp {
//USERS DECLARATIONS.
users = [];

//USER COMPONENT CONSTRUCTOR.


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

//GET USERS SERVICE ON PAGE LOAD and BIND UI GRID.


ngOnInit() {
this._userService.getAPIUsers(this._global.baseAPIUrl +
'users/api/GetUsers').subscribe(data => this.users = data);
}
}
How to use styleUrls and styles in Angular 2?
Anil Singh 4:21 AM Edit

The Angular 2 “styles” or “styleUrls” should only be used for css rules and it is affect
the style of the template elements.

This is the best approaches to add styles directly to the components and the view encapsulation is set per
component. It is use for some situations.

Stayed Informed – Angular 2 Documentations and Examples

An example to add external styles to the components result text color is red,
Syntax –
@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
styles: ['.tbl-row-border { border: 1px solid red;}','.txt-color{color:red;}']
})

home.component.html :-

<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Angular 2 for loop typescript example - *ngFor</h5>
</div>
<div class="ibox-title">
<input type="text" [(value)]="values" (keyup)="onKeyUp($event)" /> <strong>Resut-
{{values}}</strong>
</div>
<div class="ibox-content">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name </th>
<th>SiteUrl </th>
<th>Actions </th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of userlist; let i = index" class="tbl-row-border">
<td>{{user.Id}}</td>
<td>{{user.name}}</td>
<td><a href="{{user.site}}" target="_blank">{{user.site}}</a></td>
<td><a (click)="addUser(user)">A</a>|<a
(click)="updateUser(user)">E</a>|<a (click)="deleteUser(user)">D</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>

home.component.ts :-

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


import { CommonModule } from '@angular/common';

@Component({
selector: 'home',
templateUrl: './home.component.html',
//styleUrls: ['./home.component.css'],
styles: ['.tbl-row-border { border: 1px solid red;}']
})

export class HomeComponent {


userlist: Users[];

constructor() {
this.userlist = [{ Id: '1001', name: 'Anil SIngh', site: 'http://www.code-sample.com' },
{ Id: '1002', name: 'Alok', site: 'http://www.code-view.com' },
{ Id: '1003', name: 'Reena', site: 'http://www.code-sample.xyz' },
{ Id: '1004', name: 'Dilip', site: 'http://www.codefari.com' },
];
}

values = '';
onKeyUp(event: any) {
this.values = event.target.value;
};

addUser(user) {
alert(JSON.stringify(user));
};

updateUser(user) {
alert(JSON.stringify(user));
};

deleteUser(user) {
alert(JSON.stringify(user));
};
}

export class Users {


Id: String;
name: String;
site: String;
}

app.module.ts :-
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component';
import { HomeComponent } from './components/home/home.component';
import { HeaderComponent } from './components/shared/header/header.component';
import { MenuComponent } from './components/menu/menu.component';

@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
HomeComponent,
HeaderComponent,
MenuComponent
],
imports: [
UniversalModule, // Must be first import. This automatically imports BrowserModule,
HttpModule, and JsonpModule too.
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: '**', redirectTo: 'home' }
])
]
})
export class AppModule {
}

Angular 2 Routing Concepts and Examples


Anil Singh 10:30 PM Edit

This post helps us to learn application “Routings” in Angular 2. In the below


routing example I am using Angular 2 for the client side and ASP.NET Core with
single page application (SPA) for the server application.

“The Router is use to map applications URLs to application components. There are
three main components that you are using to configure routing.”

1. Routes: - It uses to describe our application's Routes.


2. Router Imports: - It uses to import our application's Routes.

3. RouterOutlet: - It is a placeholder component and use to get expanded to each


route's content.

4. RouterLink: - It is use to link to application's routes.

Routes: - The Routes is uses to describe our application's Routes. The


“RouterModule.forRoot” method in the module imports to configure the router.

Five concepts that need Routes Representation

1. Path (a part of the URL)

2. Route Parameters

3. Query/Matrix Parameters

4. Name outlets

5. A tree of route segments targeting outlets

Syntax:-
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE
PARAMETER.
{ path: 'login', component: LoginComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '**', redirectTo: 'home' }

])
Example,
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
HomeComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS
BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.
RouterModule.forRoot([ //RouterModule.forRoot method in the module imports
to configure the router.
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE
PARAMETER.
{ path: 'login', component: LoginComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '**', redirectTo: 'home' }
]),
FormsModule,
ReactiveFormsModule
]

})
Router Imports - The Angular Router is an optional service that presents a
particular component view for a given URL i.e.

import { RouterModule, Routes } from '@angular/router';

Example,
import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { UniversalModule } from 'angular2-universal';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpModule } from '@angular/http';

import { AppComponent } from './components/app/app.component';

import { HomeComponent } from './components/home/home.component';

import { HeaderComponent } from './components/shared/header/header.component';

import { MenuComponent } from './components/menu/menu.component';

import { LoginComponent } from './components/login/login.component';

import { RegistrationComponent } fro


m './components/registration/registration.component'

@NgModule({

bootstrap: [ AppComponent ],

declarations: [
AppComponent,

HomeComponent,

HeaderComponent,

MenuComponent,

LoginComponent,

RegistrationComponent

],

imports: [

UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS


BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.

RouterModule.forRoot([ //RouterModule.forRoot method in the module


imports to configure the router.

{ path: '', redirectTo: 'home', pathMatch: 'full' },

{ path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE


PARAMETER.

{ path: 'login', component: LoginComponent },

{ path: 'registration', component: RegistrationComponent },

{ path: '**', redirectTo: 'home' }

]),

FormsModule,

ReactiveFormsModule

})

Router-outlet directive: - Router-outlet directive is used to render the


components for specific location of your applications. Both the template and
templateUrl render the components where you use this directive.

Syntax :- <router-outlet></router-outlet>

Example
<div class='container'>
<div class='row'>
<router-outlet></router-outlet>
</div>
</div>

The Route Params: - The route parameter is used to map given URL's parameters
based on the rout URLs and it is an optional parameters for that route.

Syntax: - params: {[key: string]: string}

Example
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
HomeComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS
BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.
RouterModule.forRoot([ //ROUTERMODULE.FORROOT METHOD IN THE MODULE
IMPORTS TO CONFIGURE THE ROUTER.
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE
PARAMETER.
{ path: 'login', component: LoginComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '**', redirectTo: 'home' }
]),
FormsModule,
ReactiveFormsModule
]

})

Router-link directive: - Router-link directive is used to link a specific part of your


applications.

Syntax :- <router-link></router-link>

Example,
<ul class='nav navbar-nav'>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/login']">
<span class='glyphicon glyphicon-Login'></span> Login
</a>
</li>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/registration']">
<span class='glyphicon glyphicon-Register'></span> Register
</a>
</li>
<li [routerLinkActive]="['link-active']">
<a [routerLink]="['/Billing']">
<span class='glyphicon glyphicon-Billing'></span> Billing
</a>
</li>

</ul>

Angular2 cookies | angular2 http cookies | angular2 http


get set cookie
Anil Singh 11:30 PM Edit

Angular 2 cookies concept is very similar to the Angular 1.x but


Angular2 added only one extra method to remove all cookies i.e.
removeAll()

The All cookie methods are

1. get()
2. getObject()
3. getAll()
4. put()
5. putObject()
6. remove()
7. removeAll() - This is new one in angular 2

get() :- This method is returns the value of given cookie key.


getObject() :- This method is returns the desterilized value of given cookie key.
getAll() :- This method is returns a key value object with all the cookies.
put() :- This method is use to set a value for given cookie key.
putObject() :- This method is use to serializes and set a value for given cookie key.
remove() :-This method is use to remove given cookie.
removeAll() :-This method is use to remove all cookies.

Stayed Informed - 69 Best Angular 2 Interview Questions and Answers

You can create your own functions to get cookie value, set cookie value
and delete cookie value.

Two ways to create cookies -

1. You can inject a service in the components providers.

2. You can get it via npm.

To install ng2-cookies library, run the below given code i.e.

npm install angular2-cookie --save

You can include angular2-cookie library for the same which has given below.

<script src="~/cookie/angular2-cookie.min.js"></script>

Example - You can get it via npm

The full example for creating your own functions as,


@Component({
selector: 'cookie-consent',
template: cookieconsent_html,
styles: [cookieconsent_css]
})
export class CookieConsent {
private isConsented: boolean = false;

constructor() {
this.isConsented = this.getCookie(COOKIE_CONSENT) === "1";
}

private getCookie(name: string) {


let ca: Array<string> = document.cookie.split(';');
let caLen: number = ca.length;
let cookieName = name + "=";
let c: string;

for (let i: number = 0; i < caLen; i += 1) {


c = ca[i].replace(/^\s\+/g, "");
if (c.indexOf(cookieName) == 0) {
return c.substring(cookieName.length, c.length);
}
}
return "";
}

private deleteCookie(name) {
this.setCookie(name, "", -1);
}

private setCookie(name: string, value: string, expireDays: number, path: string = "") {
let d:Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
let expires:string = "expires=" + d.toUTCString();
document.cookie = name + "=" + value + "; " + expires + (path.length > 0 ? "; path="
+ path : "");
}

private consent(isConsent: boolean, e: any) {


if (!isConsent) {
return this.isConsented;
} else if (isConsent) {
this.setCookie(COOKIE_CONSENT, "1", COOKIE_CONSENT_EXPIRE_DAYS);
this.isConsented = true;
e.preventDefault();
}
}
}

Example 2 - You can inject a service in the components providers


//Use of Angular 2 cookies, the example in detail as give below.

import {Component} from '@angular2/core';


import {Cookie} from '@angular2-cookie/core';
@Component({
selector: 'my-cookie-app',
template: '<div>Cookies in Angular 2</div>',
providers: [Cookie]
})

export class App_Component {


constructor(private _cookie:Cookie){}

getCookie(key: string){
return this._cookie.get(key);
}

getCookieObject(key: string){
return this._cookie.getObject(key);
}
}

//And other are available methods [put(), putObject(), remove() and removeAll()]
//All methods work similar like above methods.

Dependency Injection (DI) in Angular 2 [Why


@Injectable()?]
Anil Singh 11:30 PM Edit

Dependency Injection is a powerful pattern for managing code dependencies.

Angular 2 Dependency Injection consists of three things.

1. Injector

2. Provider

3. Dependency
Injector :- The injector object use to create instances of dependencies.

Provider :- A provider is help to injector for create an instance of a dependency. A provider


takes a token and maps that to a factory function that creates an object.

Dependency :- A dependency is the type of which an object should be created.

When use @Inject()? When Use @Injectable ()? @Injectable() vs.


@Inject() ?

How to use Dependency Injection (DI) correctly in Dependency Injection (DI) in


Angular 2? Angular 2?

@Injectable() marks a class as available to an injector for instantiation. An injector


reports an error when trying to instantiate a class that is not marked
as @Injectable().

Injectors are also responsible for instantiating components. At the run-time the
injectors can read class metadata in the JavaScript code and use the constructor
parameter type information to determine what things to inject.

How to use Dependency Injection (DI) correctly in Angular 2?

The basics Steps of Dependency injection,

1. A class with @Injectable() to tell angular 2 that it’s to be injected “UserService”.

2. A class with a constructor that accepts a type to be injected.


Example, UserService marked as @Injectable as,
import {Injectable, bind} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable() /* This is #Step 1 */


export class UserService {
constructor(http: URL /* This is #Step 2 */ ) {
this.http = URL;
}
}

Example as,
import {Injectable} from "@angular/core";

@Injectable()
export class InjectToService {
id: string;

constructor() {
this.resetPasscode();
}

resetPasscode(): void {
this.id = this.generatePasscode();
}

private generatePasscode(): string {


var date = new Date().getTime();

var pascode = '00X000-00000-7000-Z0000-00000'.replace(/[xy]/, function(f) {


var random = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (f == '0' ? random : (random & 0x3 | 0x8)).toString(16);
});

return pascode;
};
}

Angular 2 @NgModel [Purpose Of Root Module & Export


Module]
Anil Singh 9:30 PM Edit
The @NgModule is a new decorator. This module is recently added in Angular 2.

The @NgModule is a class and work with the @NgModule decorator function.
@NgModule takes a metadata object that tells Angular “how to compile and run
module code”.

The @NgModules page guides you from the most elementary @NgModule to
a multi-facetedsample with lazy modules.

Stayed Informed – Angular 2 vs. Angular 1


Stayed Informed - Angular 4 vs. Angular 2

The @NgModule main use to simplify the way you define and manage the
dependencies in your applications and using @NgModule you can consolidate
different components and services into cohesive blocks of functionality.

The Basic Example of @NgModule as,


@NgModule({
imports: [BrowserModule],
declarations: [YourComponent],
bootstrap: [YourComponent]
})
class YourAppModule {}

The @NgModule is a way to organize your dependencies for

1. Compiler

2. Dependency Injection
The declarations of @NgModule.declarations as,
@NgModule({
declarations: [
AppComponent,
YourComponent,
YourDirective,
YourPipe,
...OTHER DIRECTIVES AND SO ON.
]
})

The @NgModule providers as,


@NgModule({
providers: [
YourService,
SomeLibraryService,
],
})

The @NgModule exporting as,


@NgModule({
declarations: [YourComponent, YourPipe]
exports: [YourComponent, YourPipe],
providers: [YourService]
})
export class YourModule { }

Why Angular 2 modules needed?

An Angular @NgModule allows us to define a context for compiling templates.

Why @NgModule?

1. Easy to use Components

2. Easy to use Directives


3. Easy to use Pipes

4. Providers’ Inheritance

5. Library Architecture

6. Easy to migrate from angular.module()

7. So on

What is a Root Module?

Each application only has one root module and each component, directive and pipe
should only be associated to a single module. This one is the main reason.

How Should We Organize Modules?

There are no standard ways to group modules, but the recommendations are,

1. Features as a module

2. Shared utilities as a module

Module’s Features:-

For example, suppose that your application has customer, product and feature.
Each module has some components, directives and pipes.

Module’s Utility:-

For the functions or features that can be shared across modules and application,
consider creating a shared module.

How to declaration Module?


import {NgModule, ApplicationRef} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {MaterialModule} from '@angular2-material/module';
import {AppComponent} from './app.component';

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, CommonModule, FormsModule, MaterialModule],
entryComponents: [AppComponent]
})
class AppModule {
constructor(appRef: ApplicationRef) {
appRef.bootstrap(AppComponent);
}
}

//Bootstrapping

import {AppModule} from './app.module';


import {platformBrowserDynamic} from '@angular/browser-platform-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule);

@NgModule
class NgModule {
declarations: Array<ComponentType | DirectiveType | PipeType>;
imports: Array<ModuleType | ModuleWithProviders>;
exports: Array<ComponentType | DirectiveType | PipeType | ModuleType>;
providers: Array<Providers | Array<any> >;
entryComponents: Array<ComponentType>;
schemas: Array<any>;
}

What is One Root Module?

When we create an Angular 2 app, we define a root module. We learned about this
in the previous post. This root module is defined with @NgModule and works quite
well for small apps.

// app.module.ts
@NgModule({
imports: [BrowserModule, FormsModule, HttpModule],
declarations: [
AppComponent,
VehicleListComponent,
VehicleSelectionDirective,
VehicleSortingPipe
],
providers: [
LoggerService,
VehicleService,
UserProfileService
],
bootstrap: [AppComponent],
})
export class AppModule { }

Our root module declares our components, pipes and directives.

Our root module imports common features from the Angular 2 BrowserModule,
FormsModule, and HttpModule.

Final Conclusions are,

1. The Use of NgModule.providers

a. Remove Component.providers

2. Use NgModule.declarations

a. Remove Component.directives/pipes

3. Keep a single scope

4. Use modules

a. Http, Forms, Router, and so on.

5. Make modules

6. Module as a Library
Angular 2 @NgModel [Purpose Of Root Module & Export
Module]
Anil Singh 9:30 PM Edit

The @NgModule is a new decorator. This module is recently added in Angular 2.

The @NgModule is a class and work with the @NgModule decorator function.
@NgModule takes a metadata object that tells Angular “how to compile and run
module code”.

The @NgModules page guides you from the most elementary @NgModule to
a multi-facetedsample with lazy modules.

Stayed Informed – Angular 2 vs. Angular 1


Stayed Informed - Angular 4 vs. Angular 2

The @NgModule main use to simplify the way you define and manage the
dependencies in your applications and using @NgModule you can consolidate
different components and services into cohesive blocks of functionality.

The Basic Example of @NgModule as,


@NgModule({
imports: [BrowserModule],
declarations: [YourComponent],
bootstrap: [YourComponent]
})
class YourAppModule {}

The @NgModule is a way to organize your dependencies for


1. Compiler

2. Dependency Injection

The declarations of @NgModule.declarations as,


@NgModule({
declarations: [
AppComponent,
YourComponent,
YourDirective,
YourPipe,
...OTHER DIRECTIVES AND SO ON.
]
})

The @NgModule providers as,


@NgModule({
providers: [
YourService,
SomeLibraryService,
],
})

The @NgModule exporting as,


@NgModule({
declarations: [YourComponent, YourPipe]
exports: [YourComponent, YourPipe],
providers: [YourService]
})
export class YourModule { }

Why Angular 2 modules needed?

An Angular @NgModule allows us to define a context for compiling templates.

Why @NgModule?
1. Easy to use Components

2. Easy to use Directives

3. Easy to use Pipes

4. Providers’ Inheritance

5. Library Architecture

6. Easy to migrate from angular.module()

7. So on

What is a Root Module?

Each application only has one root module and each component, directive and pipe
should only be associated to a single module. This one is the main reason.

How Should We Organize Modules?

There are no standard ways to group modules, but the recommendations are,

1. Features as a module

2. Shared utilities as a module

Module’s Features:-

For example, suppose that your application has customer, product and feature.
Each module has some components, directives and pipes.

Module’s Utility:-

For the functions or features that can be shared across modules and application,
consider creating a shared module.
How to declaration Module?
import {NgModule, ApplicationRef} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {MaterialModule} from '@angular2-material/module';
import {AppComponent} from './app.component';

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, CommonModule, FormsModule, MaterialModule],
entryComponents: [AppComponent]
})
class AppModule {
constructor(appRef: ApplicationRef) {
appRef.bootstrap(AppComponent);
}
}

//Bootstrapping

import {AppModule} from './app.module';


import {platformBrowserDynamic} from '@angular/browser-platform-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule);

@NgModule
class NgModule {
declarations: Array<ComponentType | DirectiveType | PipeType>;
imports: Array<ModuleType | ModuleWithProviders>;
exports: Array<ComponentType | DirectiveType | PipeType | ModuleType>;
providers: Array<Providers | Array<any> >;
entryComponents: Array<ComponentType>;
schemas: Array<any>;
}

What is One Root Module?

When we create an Angular 2 app, we define a root module. We learned about this
in the previous post. This root module is defined with @NgModule and works quite
well for small apps.

// app.module.ts
@NgModule({
imports: [BrowserModule, FormsModule, HttpModule],
declarations: [
AppComponent,
VehicleListComponent,
VehicleSelectionDirective,
VehicleSortingPipe
],
providers: [
LoggerService,
VehicleService,
UserProfileService
],
bootstrap: [AppComponent],
})
export class AppModule { }

Our root module declares our components, pipes and directives.

Our root module imports common features from the Angular 2 BrowserModule,
FormsModule, and HttpModule.

Final Conclusions are,

1. The Use of NgModule.providers

a. Remove Component.providers

2. Use NgModule.declarations

a. Remove Component.directives/pipes

3. Keep a single scope

4. Use modules

a. Http, Forms, Router, and so on.

5. Make modules

6. Module as a Library

You might also like