Angular Interview Questions
Angular Interview Questions
Stayed Informed – Angular 2 vs. ReactJs and 13 Best Advantages for Angular2
1. Chrome
2. Firefox
3. Opera
4. Safari
Angular 2 Features –
Directives
Dependency Injection
Used of TypeScript
Generics
And So on.....
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.
Forms and Validations- Angular 2 forms and validations are an important aspect
of front-end development.
5. Angular2 provide simpler APIs, lazy loading and easier to application debugging.
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.
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,
5. Angular2 provide simpler APIs, lazy loading and easier to application debugging.
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.
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.
3. Add the route to top level routing and takes routes array and configures the router.
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.
2. Consider lazy loading instead of fully bundled app if the app size is more.
5. Keep in mind, your application’s 3rd party unused library. If exist and not used,
removed from your application.
As like your other web applications, you should flow in angular 2 applications also.
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
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).
Angular 2 Constructors:-
Angular 2 ngOnInit:-
Example as,
import {Component, OnInit} from '@angular/core';
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.
@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 Constructors:-
@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();
}
}
The ngOnInit is called after the constructor and ngOnInit is called after
the first ngOnChanges.
ngOnInit(){
}
}
Angular 2 ngOnDestroy :-
Example as,
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {
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
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.
Steps –
3. Result
Create Global Variables :- “app.global.ts”
@Injectable()
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
})
export class UserComponent {
//USERS DECLARATIONS.
users = [];
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));
“user.server.ts” :-
import 'rxjs/add/operator/map';
//BEGIN-REGION - USERSERVICE
@Injectable()
getAPIUsers(apiUrl) {
return this._http.get(apiUrl).map((data: Response) => data.json());
getAppUsers(apiUrl) {
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,
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,
8. Pipes - Angular 4 introduced a new “titlecase” pipe “|” and use to changes the
first letter of each word into the uppercase.
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.
//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
2. Watch mode
7. Smooth upgrades
8. Tree-Shakeable components
5. Improvement on Logging
6. Improvement on Caching
3. Added add default updateOn values for groups and arrays to form
controls
Added new router life cycle events for Guards and Resolvers -
1. GuardsCheckStart,
2. GuardsCheckEnd,
3. ResolveStart and
4. ResolveEnd
3. Don't strip CSS source maps. This is the compiler related fix
7. Fix platform-browser-dynamic
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.
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
Simply run the blow command and update your existing Angular project-
Alternatively, you can use the command - ng update rxjs to update RxJS and install
the rxjs-compat package automatically.
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/throttle';
And
Instead of
import 'rxjs/add/observable/of';
Instead of-
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/throttle';
.throttle(...)
.subscribe(...);
You can use the new pipe () method,
yourObservable
.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.
The above command helps you to update your existing “.angular-cli.json” file to the
new “angular.json” file.
<template [ngIf]="IsAdmin">
</template>
<ng-template [ngIf]="IsAdmin">
</ng-template>
Instead of
//my.service.ts
//In app.module.ts
@NgModule({
declarations: [],
})
//my.service.ts
@Injectable({providedIn: 'root'})
@NgModule({
declarations: [],
providers: [] // Service does not need to be added here
})
The second one obviously saves you some lines of code as compare to previous
code.
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.
myForm: FormGroup;
ngOnInit() {
this.myForm = this.fb.group({
options: this.fb.array([],
[MyValidators.minCount, MyValidators.maxCount])
});
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 -
And
onChange(value) {
Now Use -
And
onChange(NgModel: NgModel) {
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.
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.
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.
Example of Components
@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
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);
};
}
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
@Components @Directive
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.
@Component({
selector: 'hello-world'
})
@View({
})
class hello {
<hello-world></hello-world>
@Component({
selector: 'user-detail'
})
@View({
})
class userDetail {
<user-detail></user-detail>
Angular 2 Constructors:-
@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();
}
}
The ngOnInit is called after the constructor and ngOnInit is called after
the first ngOnChanges.
ngOnInit(){
}
}
Angular 2 ngOnDestroy :-
Example as,
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {
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
@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.
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>
Example 2,
@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;
@Output decorates output properties and its binds a property of the type of
angular EventEmitter.
Stayed Informed - Angular 2 @Inputs
@Component(...)
class yourComponent {
addUser(event) {
}
}
<button (click)="addUser()">Click</button>
<button (click)="addUser($event)"></button>
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);
@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();
Syntax:-
<div [hidden]="!active">
Hello, this is active area!
</div>
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;
}
1. $rootScope,
2. $scope,
3. $emit,
4. $broadcast
@Injectable()
export class MyService {
constructor() { }
}
@Component({
selector: 'my-app',
templateUrl: './myApp.component.html'
})
export class MyAppComponent { }
@Component({
selector: '<my-component></my-component>',
templateUrl: 'app/component.html',
providers: [MyService]
})
@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
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.
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>
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 –
1. @ViewChild()
2. @ViewChildren()
3. @ContentChild()
4. @ContentChildren()
@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;
});
}
}
The Angular 2 is using services concept and it provide the multiple features to us
that are,
2. Services are capable of returning the data in the form promises or observables.
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.
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.
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 :-
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
UserComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
]),
FormsModule,
ReactiveFormsModule
})
//BEGIN-REGION - USERSERVICE
@Injectable()
getUsers(apiUrl) {
return this._http.get(apiUrl).map((data: Response) => data.json());
//BEGIN-REGION - USERCOMPONENT
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService]
})
//USERS DECLARATIONS.
users = [];
ngOnInit() {
this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);
user.component.html :-
<div class="row">
<div class="col-lg-12">
<div class="ibox-title">
</div>
<hr />
<div class="ibox-content">
<div class="table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name </th>
<th>Description </th>
<th>URls </th>
</tr>
</thead>
<tbody>
<td>{{user.id}}</td>
<td>{{user.login}}</td>
<td>{{user.description}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
The Angular 2 is using services concept and it provide the multiple features to us
that are,
2. Services are capable of returning the data in the form promises or observables.
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.
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.
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
UserComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
]),
FormsModule,
ReactiveFormsModule
],
providers: [UserService]
})
user.service.ts :-
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
//BEGIN-REGION - USERSERVICE
@Injectable()
getUsers(apiUrl) {
//BEGIN-REGION - USERCOMPONENT
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService]
})
//USERS DECLARATIONS.
users = [];
ngOnInit() {
this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);
<div class="col-lg-12">
<div class="ibox-title">
</div>
<hr />
<div class="ibox-content">
<div class="table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name </th>
<th>Description </th>
<th>URls </th>
</tr>
</thead>
<tbody>
<td>{{user.id}}</td>
<td>{{user.login}}</td>
<td>{{user.description}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Result :-
The Angular 2 is using services concept and it provide the multiple features to us
that are,
2. Services are capable of returning the data in the form promises or observables.
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.
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.
app.module.ts :-
import { NgModule } from '@angular/core';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
UserComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
]),
FormsModule,
ReactiveFormsModule
})
//BEGIN-REGION - USERSERVICE
@Injectable()
getUsers(apiUrl) {
//BEGIN-REGION - USERCOMPONENT
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService]
})
//USERS DECLARATIONS.
users = [];
ngOnInit() {
this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);
user.component.html :-
<div class="row">
<div class="col-lg-12">
<div class="ibox-title">
</div>
<hr />
<div class="ibox-content">
<div class="table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name </th>
<th>Description </th>
<th>URls </th>
</tr>
</thead>
<tbody>
<td>{{user.id}}</td>
<td>{{user.login}}</td>
<td>{{user.description}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Result :-
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?
What is Pipes?
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:-
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.
@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): '')
}
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.
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?
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.
@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 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.
@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 = [];
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:-
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';
@Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
//USERS DECLARATIONS.
users = [];
ngOnInit() {
this.userService.getUsers(this.userRestApiUrl).subscribe(data
=> this.users = data);
user.service.ts :-
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
//BEGIN-REGION - USERSERVICE
@Injectable()
getUsers(apiUrl) {
custom.barcode.pipe.ts :-
@Pipe({
name: 'barcode',
pure: false
})
if (!value) {
return '';
}
app.module.ts :-
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
UserComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent,
BarCodePipe,
MyPipePipe
],
imports: [
]),
FormsModule,
ReactiveFormsModule
],
providers: [UserService]
})
user.component.html :-
<div class="row">
<div class="col-lg-12">
<div class="ibox-title">
<hr />
<div class="ibox-content">
<div class="table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Name </th>
<th>Description </th>
<th>URls </th>
</tr>
</thead>
<tbody>
<td>{{user.login}}</td>
<td>{{user.description}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Result –
Angular 2 Directives [Components, Structural, Attribute
Directives]
Anil Singh 12:00 AM Edit
@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.
onKey(event) {
this.isActive = true;
this.values += event.target.value;
}
}
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
1. Separations of code
2. Easy debugging
The upcoming offline template compiler will inline templates linked by templateUrl.
@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 = [];
@Component({
selector: 'users-app',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
providers: [UserService, AppGlobals],
})
export class UsersApp {
//USERS DECLARATIONS.
users = [];
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.
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 :-
@Component({
selector: 'home',
templateUrl: './home.component.html',
//styleUrls: ['./home.component.css'],
styles: ['.tbl-row-border { border: 1px solid red;}']
})
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));
};
}
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 {
}
“The Router is use to map applications URLs to application components. There are
three main components that you are using to configure routing.”
2. Route Parameters
3. Query/Matrix Parameters
4. Name 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.
Example,
import { NgModule } from '@angular/core';
@NgModule({
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
HomeComponent,
HeaderComponent,
MenuComponent,
LoginComponent,
RegistrationComponent
],
imports: [
]),
FormsModule,
ReactiveFormsModule
})
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.
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
]
})
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>
1. get()
2. getObject()
3. getAll()
4. put()
5. putObject()
6. remove()
7. removeAll() - This is new one in angular 2
You can create your own functions to get cookie value, set cookie value
and delete cookie value.
You can include angular2-cookie library for the same which has given below.
<script src="~/cookie/angular2-cookie.min.js"></script>
constructor() {
this.isConsented = this.getCookie(COOKIE_CONSENT) === "1";
}
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 : "");
}
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.
1. Injector
2. Provider
3. Dependency
Injector :- The injector object use to create instances of dependencies.
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.
Example as,
import {Injectable} from "@angular/core";
@Injectable()
export class InjectToService {
id: string;
constructor() {
this.resetPasscode();
}
resetPasscode(): void {
this.id = this.generatePasscode();
}
return pascode;
};
}
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.
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.
1. Compiler
2. Dependency Injection
The declarations of @NgModule.declarations as,
@NgModule({
declarations: [
AppComponent,
YourComponent,
YourDirective,
YourPipe,
...OTHER DIRECTIVES AND SO ON.
]
})
Why @NgModule?
4. Providers’ Inheritance
5. Library Architecture
7. So on
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.
There are no standard ways to group modules, but the recommendations are,
1. Features 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.
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, CommonModule, FormsModule, MaterialModule],
entryComponents: [AppComponent]
})
class AppModule {
constructor(appRef: ApplicationRef) {
appRef.bootstrap(AppComponent);
}
}
//Bootstrapping
@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>;
}
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 imports common features from the Angular 2 BrowserModule,
FormsModule, and HttpModule.
a. Remove Component.providers
2. Use NgModule.declarations
a. Remove Component.directives/pipes
4. Use modules
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 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.
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.
2. Dependency Injection
Why @NgModule?
1. Easy to use Components
4. Providers’ Inheritance
5. Library Architecture
7. So on
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.
There are no standard ways to group modules, but the recommendations are,
1. Features 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
@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>;
}
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 imports common features from the Angular 2 BrowserModule,
FormsModule, and HttpModule.
a. Remove Component.providers
2. Use NgModule.declarations
a. Remove Component.directives/pipes
4. Use modules
5. Make modules
6. Module as a Library