1. Why were client-side frameworks like Angular introduced?
Back in the day, web developers used VanillaJS and jQuery to develop dynamic websites but, as
the logic of one's website grew, the code became more and more tedious to maintain. For
applications that use complex logic, developers had to put in extra effort to maintain separation
of concerns for the app. Also, jQuery did not provide facilities for data handling across views.
For tackling the above problems, client-side frameworks like Angular came into the picture,
which made life easier for the developers by handling separation of concerns and dividing code
into smaller bits of information (In the case of Angular, called Components).
Client-side frameworks allow one to develop advanced web applications like Single-Page-
Application. Not that we cannot develop SPAs using VanillaJS, but by doing so, the development
process becomes slower.
2. How does an Angular application work?
Every Angular app consists of a file named angular.json. This file will contain all the
configurations of the app. While building the app, the builder looks at this file to find the entry
point of the application. Following is an image of the angular.json file:
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-starter",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/style.css"
]
}
}
Inside the build section, the main property of the options object defines the entry point of the
application which in this case is main.ts.
The main.ts file creates a browser environment for the application to run, and, along with this, it
also calls a function called bootstrapModule, which bootstraps the application. These two steps
are performed in the following order inside the main.ts file:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule)
In the above line of code, AppModule is getting bootstrapped.
The AppModule is declared in the app.module.ts file. This module contains declarations of all
the components.
Below is an example of app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [],
bootstrap: [AppComponent]
})
export class AppModule { }
As one can see in the above file, AppComponent is getting bootstrapped.
This component is defined in app.component.ts file. This file interacts with the webpage and
serves data to it.
Below is an example of app.component.ts file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}
Each component is declared with three properties:
1. Selector - used for accessing the component
2. Template/TemplateURL - contains HTML of the component
3. StylesURL - contains component-specific stylesheets
After this, Angular calls the index.html file. This file consequently calls the root component that
is app-root. The root component is defined in app.component.ts.
This is how the index.html file looks:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
The HTML template of the root component is displayed inside the <app-root> tags.
This is how every angular application works.
3. What are some of the advantages of Angular over other frameworks?
Features that are provided out of the box - Angular provides a number of built-in features
like,routing, state management, rxjs library and http services straight out of the box. This means
that one does not need tolook for the above stated features separately. They are allprovided
with angular.
Declarative UI - Angular uses HTML to render the UI of an application. HTML isa declarative
language and is much easier to use than JavaScript.
Long-term Google support - Google announced Long-term support for Angular. This means
that Google plans to stick with Angular and further scale up its ecosystem.
4. List out differences between AngularJS and Angular
Architecture :
AngularJS uses MVC or Model-View-Controller architecture, where the Model contains the
business logic, Controller processes information and View shows the information present in the
Model.
Angular replaces controllers with Components. Components are nothing but directives with a
predefined template.
Language :
AngularJS uses JavaScript language, which is a dynamically typed language.
Angular uses TypeScript language, which is a statically typed language and is a superset of
JavaScript. By using statically typed language, Angular provides better performance while
developing larger applications.
Mobile Support :
AngularJS does not provide mobile support.
Angular is supported by all popular mobile browsers.
Structure :
While developing larger applications, the process of maintaining code becomes tedious in the
case of AngularJS.
In the case of Angular, it is easier to maintain code for larger applications as it provides a better
structure.
Expression Syntax :
While developing an AngularJS application, a developer needs to remember the correct ng-
directive for binding an event, or a property. Whereas in Angular, property binding is done using
"[ ]" attribute and event binding is done using "( )" attribute.
5. What is AOT compilation? What are the advantages of AOT?
Every Angular application consists of components and templates which the browser cannot
understand. Therefore, all the Angular applications need to be compiled first before running
inside the browser.
Angular provides two types of compilation:
JIT(Just-in-Time) compilation
AOT(Ahead-of-Time) compilation
In JIT compilation, the application compiles inside the browser during runtime.
Whereas in the AOT compilation, the application compiles during the build time.
The advantages of using AOT compilation are:
Since the application compiles before running inside the browser, the browser loads the
executable code and renders the application immediately, which leads to faster rendering.
In AOT compilation, the compiler sends the external HTML and CSS files along with the
application, eliminating separate AJAX requests for those source files, which leads to fewer
ajax requests.
Developers can detect and handle errors during the building phase, which helps
in minimizing errors.
The AOT compiler adds HTML and templates into the JS files before they run inside the
browser. Due to this, there are no extra HTML files to be read, which provide better
security to the application.
By default, angular builds and serves the application using JIT compiler:
ng build
ng serve
For using AOT compiler following changes should be made:
ng build --aot
ng serve –aot
6. Explain Components, Modules and Services in Angular
For better understanding, I would like you to create an Angular application by running the
following inside the command terminal:
ng new angularApp
The above command will create an angular application in the directory.
Next, let's move on to understand Components, Modules, and Services.
Components
In Angular, components are the basic building blocks, which control a part of the UI for any
application.
A component is defined using the @Component decorator. Every component consists of three
parts, the template which loads the view for the component, a stylesheet which defines the look
and feel for the component, and a class that contains the business logic for the component.
For creating a component, inside the command terminal, navigate to the directory of the
application created, and run the following command:
ng generate component test
Or
ng g c test
One can see the generated component inside src/app/test folder. The component will be
defined inside test.component.ts and this is how it looks:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export lass TestComponent implements OnInit {
constructor() {}
ngOnInit() {
}
}
As we can see in the above image, our component is defined with @Component decorator.
Modules
A module is a feature area in angular application . A module is a place where we can group
components, directives, services, and pipes. Module decides whether the components,
directives, etc can be used by other modules, by exporting or hiding these elements. Every
module is defined with a @NgModule decorator.
By default, modules are of two types:
Root Module
Feature Module
Every application can have only one root module whereas, it can have one or more feature
modules.
A root module imports BrowserModule, whereas a feature module imports CommonModule.
In the application that we created before, one can see that the root module is defined
inside app.module.ts and this is how it looks:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestComponent } from './test/text.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
We can see in the above image that the component we created earlier is already imported in
the declarations array.
To create a feature module, run the following command:
ng g m test-module
The module is created inside the src/app/test-module/test-module.module.ts file:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class TestModuleModule { }
As one can see, CommonModule is imported since this is a feature module.
Services : Services are objects which get instantiated only once during the lifetime of an
application. The main objective of a service is to share data, functions with different
components of an Angular application.
A service is defined using a @Injectable decorator. A function defined inside a service can be
invoked from any component or directive.
To create a service, run the following command:
ng g s test-service
The service will be created inside src/app/test-service.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestServiceService {
constructor() { }
Any method/function defined inside the TestServiceService class can be directly used inside any
component by just importing the service.
7. What are lifecycle hooks in Angular? Explain a few lifecycle hooks.
Every component in Angular has a lifecycle, different phases it goes through from the time of
creation to the time it's destroyed. Angular provides hooks to tap into these phases and trigger
changes at specific phases in a lifecycle.
ngOnChanges( ) This hook/method is called before ngOnInit and whenever one or more input
properties of the component changes.
This method/hook receives a SimpleChanges object which contains the previous and current
values of the property. It is triggered when @input or @Output change
ngOnInit( ) This hook gets called once, after the ngOnChanges hook.
It initializes the component and sets the input properties of the component.
ngDoCheck( ) It gets called after ngOnChanges and ngOnInit and is used to detect and act on
changes that cannot be detected by Angular.
We can implement our change detection algorithm in this hook.
ngAfterContentInit( ) It gets called after the first ngDoCheck hook. This hook responds after the
content gets projected inside the component.
ngAfterContentChecked( ) It gets called after ngAfterContentInit and every
subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ) It responds after a component's view, or a child component's view is
initialized.
ngAfterViewChecked( ) It gets called after ngAfterViewInit, and it responds after the
component's view, or the child component's view is checked.
ngOnDestroy( ) It gets called just before Angular destroys the component. This hook can be used
to clean up the code and detach event handlers.
Let’s understand how to use ngOnInit hook, since it’s the most oftenly used hook. If one has to
process lot of data during component creation, it’s better to do it inside ngOnInit hook rather
than the constructor:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
this.processData();
}
processData(){
// Do something..
}
As you can see we have imported OnInit but we have used ngOnInit function. This principle
should be used with the rest of the hooks as well.
8. Explain string interpolation and property binding in Angular.
String interpolation and property binding are parts of data-binding in Angular.
Data-binding is a feature in angular, which provides a way to communicate between the
component(Model) and its view(HTML template).
Data-binding can be done in two ways, one-way binding and two-way binding.
In Angular, data from the component can be inserted inside the HTML template. In one-way
binding, any changes in the component will directly reflect inside the HTML template but, vice-
versa is not possible. Whereas, it is possible in two-way binding.
String interpolation and property binding allow only one-way data binding.
String interpolation uses the double curly braces {{ }} to display data from the component.
Angular automatically runs the expression written inside the curly braces, for example, {{ 2 + 2 }}
will be evaluated by Angular and the output 4, will be displayed inside the HTML template.
Using property binding, we can bind the DOM properties of an HTML element to a component's
property. Property binding uses the square brackets [ ] syntax.
9. How are Angular expressions different from JavaScript
expressions?
The first and perhaps, the biggest difference is that Angular expressions allow us to write
JavaScript in HTML which is not the case when it comes to JavaScript expressions.
Next, Angular expressions are evaluated against a local scope object whereas JavaScript
expressions against global window object. Let's understand that better with an example :
Consider the following component named test:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
message:string = “Hello world”;
constructor() { }
ngOnInit() {
}
}
As one can see that Angular expression is used to display message property of a component.
Since we are using Angular expressions, in the present template, we cannot access a property
outside of its local scope, which in this case is TestComponent.
This proves that Angular expressions are always evaluated based on scope object rather than
the global object.
Next difference is how Angular expressions handle null and undefined.
Consider the following JavaScript example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Test</title>
</head>
<body>
<div id="foo"><div>
</body>
<script>
'use strict';
let bar = {};
document.getElementById('foo').innerHTML = bar.x;
</script>
</html>
If you run the above code, you will see undefined displayed on the screen. Although it’s not
ideal to leave any property undefined, the user does not need to see this.
Now consider the following Angular example:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:object = {};
constructor() { }
ngOnInit() {
}
If you render the above component, you will not see undefined being displayed on the screen.
Next, in Angular expressions one cannot use loops, conditionals and exceptions.
The difference which makes Angular expressions quite beneficial is the use of pipes. Angular
uses pipes(called filters in AngularJS), which can be used to format data before displaying it.
Let’s see one predefined pipe in action:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new',
template: `
<h4>{{message | lowercase}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:string = "HELLO WORLD";
constructor() { }
ngOnInit() {
}
In the above code we have used a predefined pipe called lowercase, which transforms all the
letters in lowercase. Therefore, if you render the above component, you will see “hello world”
being displayed.
In contrast, JavaScript does not have the concept of pipes.
10. How are observables different from promises?
The first difference is that an Observable is lazy whereas a Promise is eager.
Promise Observable
Emits multiple values over a period of
Emits a single value
time
Lazy. An observable is not called until
Not Lazy
we subscribe to the observable
Can be cancelled by using the
Cannot be cancelled
unsubscribe() method
Observable provides operators like
map, forEach, filter, reduce, retry,
retryWhen etc.
Consider the following Observable:
const observable = rxjs.Observable.create(observer => {
console.log('Text inside an observable');
observer.next('Hello world!');
observer.complete();
});
console.log('Before subscribing an Observable');
observable.subscribe((message)=> console.log(message));
When you run the above Observable, you can see messages being displayed in the following
order:
Before subscribing an Observable
Text inside an observable
Hello world!
As you can see, observables are lazy. Observable runs only when someone subscribes to them
hence, the message “Before subscribing…” is displayed ahead of the message inside the
observable.
Now let’s consider a Promise:
const promise = new Promise((resolve, reject) => {
console.log('Text inside promise');
resolve('Hello world!');
});
console.log('Before calling then method on Promise');
greetingPoster.then(message => console.log(message));
Running the above promise, the messages will be displayed in the following order:
Text inside promise
Before calling then method on Promise
Hello world!
As you can see the message inside Promise is displayed first. This means that a promise runs
before the then method is called. Therefore, promises are eager.
The next difference is that Promises are always asynchronous. Even when the promise is
immediately resolved. Whereas an Observable, can be both synchronous and asynchronous.
The above example of an observable is the case to show that an observable is synchronous.
Let’s see the case where an observable can be asynchronous:
const observable = rxjs.Observable.create(observer => {
setTimeout(()=>{
observer.next('Hello world');
observer.complete();
},3000)
});
console.log('Before calling subscribe on an Observable');
observable.subscribe((data)=> console.log(data));
console.log('After calling subscribe on an Observable');
The messages will be displayed in the following order:
Before calling subscribe on an Observable
After calling subscribe on an Observable
Hello world!
You can see in this case, observable runs asynchronously.
The next difference is that Observables can emit multiple values whereas Promises can emit
only one value.
The biggest feature of using observables is the use of operators. We can use multiple operators
on an observable whereas, there is no such feature in a promise.
11. Angular by default, uses client-side rendering for its
applications.Can one make an angular application to render on the
server-side?
Yes, angular provides a technology called Angular Universal, which can be used to render
applications on the server-side.
The advantages of using Angular Universal are :
First time users can instantly see a view of the application. This benefits in
providing better user experience.
Many search engines expect pages in plain HTML, thus, Universal can make sure that
your content is available on every search engine, which leads to better SEO.
Any server-side rendered application loads faster since rendered pages are available to the
browser sooner.
12. What are directives in Angular?
A directive is a class in Angular that is declared with a @Directive decorator.
Every directive has its own behaviour and can be imported into various components of an
application.
When to use a directive?
Consider an application, where multiple components need to have similar functionalities. The
norm thing to do is by adding this functionality individually to every component but, this task is
tedious to perform. In such a situation, one can create a directive having the required
functionality and then, import the directive to components which require this functionality.
Types of directives : ?
(1) Component directives :
These form the main class in directives. Instead of @Directive decorator we
use @Component decorator to declare these directives. These directives have a view, a
stylesheet and a selector property.
(2) Structural directives :
These directives are generally used to manipulate DOM elements.
Every structural directive has a ‘ * ’ sign before them.
We can apply these directives to any DOM element.
Let’s see some built-in structural directives in action:
<div *ngIf="isReady" class="display_name">
{{name}}
</div>
<div class="details" *ngFor="let x of details" >
<p>{{x.name}}</p>
<p> {{x.address}}</p>
<p>{{x.age}}</p>
</div>
In the above example, we can *ngIf and *ngFor directives being used.
*ngIf is used to check a boolean value and if it’s truthy,the div element will be displayed.
*ngFor is used to iterate over a list and display each item of the list.
(3)Attribute Directives :
These directives are used to change the look and behaviour of a DOM element. Let’s understand
attribute directives by creating one:
How to create a custom directive?
We’re going to create an attribute directive:
In the command terminal, navigate to the directory of the angular app and type the following
command to generate a directive:
ng g directive blueBackground
The following directive will be generated. Manipulate the directive to look like this:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appBlueBackground]'
})
export class BlueBackgroundDirective {
constructor(el:ElementRef) {
el.nativeElement.style.backgroundColor = "blue";
}
}
Now we can apply the above directive to any DOM element:
<p appBlueBackground>Hello World!</p>
13. How does one share data between components in Angular?
Following are the commonly used methods by which one can pass data between components in
angular:
Parent to child using @Input decorator
Consider the following parent component:
@Component({
selector: 'app-parent',
template: `
<app-child [data]=data></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
data:string = "Message from parent";
constructor() { }
}
In the above parent component, we are passing “data” property to the following child
component:
import { Component, Input} from '@angular/core';
@Component({
selector: 'app-child',
template:`
<p>{{data}}</p>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() data:string
constructor() { }
}
In the child component, we are using @Input decorator to capture data coming from a parent
component and using it inside the child component’s template.
Child to parent using @ViewChild decorator
Child component:
import {Component} from '@angular/core';
@Component({
selector: 'app-child',
template:`
<p>{{data}}</p>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
data:string = "Message from child to parent";
constructor() { }
}
Parent Component
import { Component,ViewChild, AfterViewInit} from '@angular/core';
import { ChildComponent } from './../child/child.component';
@Component({
selector: 'app-parent',
template: `
<p>{{dataFromChild}}</p>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
dataFromChild: string;
@ViewChild(ChildComponent,{static:false}) child;
ngAfterViewInit(){
this.dataFromChild = this.child.data;
}
constructor() { }
}
In the above example, a property named “data” is passed from the child component to the
parent component.
@ViewChild decorator is used to reference the child component as “child” property.
Using the ngAfterViewInit hook, we assign the child’s data property to the messageFromChild
property and use it in the parent component’s template.
Child to parent using @Output and EventEmitter
In this method, we bind a DOM element inside the child component, to an event ( click event for
example ) and using this event we emit data that will captured by the parent component:
Child Component:
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
template:`
<button (click)="emitData()">Click to emit data</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
data:string = "Message from child to parent";
@Output() dataEvent = new EventEmitter<string>();
constructor() { }
emitData(){
this.dataEvent.emit(this.data);
}
}
As you can see in the child component, we have used @Output property to bind
an EventEmitter. This event emitter emits data when the button in the template is clicked.
In the parent component’s template we can capture the emitted data like this:
<app-child (dataEvent)="receiveData($event)"></app-child>
Then inside the receiveData function we can handle the emitted data:
receiveData($event){
this.dataFromChild = $event;
}
14. Explain the concept of Dependency Injection?
Dependency injection is an application design pattern which is implemented by Angular.
It also forms one of the core concepts of Angular.
So what is dependency injection in simple terms?
Let’s break it down, dependencies in angular are nothing but services which have a
functionality. Functionality of a service, can be needed by various components and directives in
an application. Angular provides a smooth mechanism by which we can inject these
dependencies in our components and directives.
So basically, we are just making dependencies which are injectable across all components of an
application.
Let’s understand how DI (Dependency Injection) works:
Consider the following service, which can be generated using:
ng g service test
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestService {
importantValue:number = 42;
constructor() { }
returnImportantValue(){
return this.importantValue;
}
}
As one can notice, we can create injectable dependencies by adding the @Injectable decorator
to a class.
We inject the above dependency inside the following component:
import { TestService } from './../test.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
value:number;
constructor(private testService:TestService) { }
ngOnInit() {
this.value = this.testService.returnImportantValue();
}
}
One can see we have imported our TestService at the top of the page. Then, we have created an
instance inside the constructor of the component and implemented
the returnImportantValue function of the service.
From the above example, we can observe how angular provides a smooth way to inject
dependencies in any component.
15. Explain MVVM architecture
MVVM architecture consists of three parts:
1.Model
2.View
3. ViewModel
Model contains the structure of an entity. In simple terms it contains data of an object.
View is the visual layer of the application. It displays the data contained inside the Model. In
angular terms, this will be the HTML template of a component.
ViewModel is an abstract layer of the application. A viewmodel handles the logic of the
application. It manages the data of a model and displays it in the view.
View and ViewModel are connected with data-binding (two-way data-binding in this case). Any
change in the view, the viewmodel takes a note and changes the appropriate data inside the
model.
What is Angular Framework?
Angular is a TypeScript-based open-source front-end platform that makes it
easy to build applications with in web/mobile/desktop. The major features of this
framework such as declarative templates, dependency injection, end to end
tooling, and many more other features are used to ease the development.
What is the difference between AngularJS and
Angular?
Angular is a completely revived component-based framework in which an
application is a tree of individual components.
Some of the major difference in tabular form
AngularJS Angular
It is based on MVC architecture This is based on Service/Controller
Introduced the TypeScript to write the
It uses JavaScript to build the application
application
Based on controllers concept This is a component based UI approach
Not a mobile friendly framework Developed considering mobile platform
Difficulty in SEO friendly application
Ease to create SEO friendly applications
development
What is TypeScript?
TypeScript is a typed superset of JavaScript created by Microsoft that adds
optional types, classes, async/await, and many other features, and compiles to
plain JavaScript. Angular built entirely in TypeScript and used as a primary
language. You can install it globally as
npm install -g typescript
Let's see a simple example of TypeScript usage,
function greeter(person: string) {
return "Hello, " + person;
}
let user = "Sudheer";
document.body.innerHTML = greeter(user);
The greeter method allows only string type as argument.
Write a pictorial diagram of Angular architecture ?
The main building blocks of an Angular application is shown in the below
diagram
What are the key components of Angular?
Angular has the below key components,
Component: These are the basic building blocks of angular application to
control HTML views.
Modules: An angular module is set of angular basic building blocks like
component, directives, services etc. An application is divided into logical pieces
and each piece of code is called as "module" which perform a single task.
Templates: This represent the views of an Angular application.
Services: It is used to create components which can be shared across the entire
application.
Metadata: This can be used to add more data to an Angular class.
What are directives?
Directives add behaviour to an existing DOM element or an existing component
instance.
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
Now this directive extends HTML element behavior with a yellow background as
below
<p myHighlight>Highlight me!</p>
What are components?
Components are the most basic UI building block of an Angular app which
formed a tree of Angular components. These components are subset of
directives. Unlike directives, components always have a template and only one
component can be instantiated per an element in a template. Let's see a simple
example of Angular component
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{title}}</h1>
<div>Learn Angular6 with examples</div>
</div> `,
})
export class AppComponent {
title: string = 'Welcome to Angular world';
}
What are the differences between Component and
Directive?
In a short note, A component(@component) is a directive-with-a-template.
Some of the major differences are mentioned in a tabular form
Component Directive
To register a component we use @Component To register directives we use
meta-data annotation @Directive meta-data annotation
Components are typically used to create UI Directive is used to add behavior to
widgets an existing DOM element
Component is used to break up the application Directive is use to design re-usable
into smaller components components
Only one component can be present per DOM Many directives can be used per
element DOM element
@View decorator or templateurl/template are
Directive doesn't use View
mandatory
What is a template?
A template is a HTML view where you can display data by binding controls to
properties of an Angular component. You can store your component's template
in one of two places. You can define it inline using the template property, or you
can define the template in a separate HTML file and link to it in the component
metadata using the @Component decorator's templateUrl property.
Using inline template with template syntax,
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: '
<div>
<h1>{{title}}</h1>
<div>Learn Angular</div>
</div>
'
})
export class AppComponent {
title: string = 'Hello World';
}
Using separate template file such as app.component.html
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
title: string = 'Hello World';
}
What is a module?
Modules are logical boundaries in your application and the application is divided
into separate modules to separate the functionality of your application. Lets take
an example of app.module.ts root module declared
with @NgModule decorator as below,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: []
})
export class AppModule { }
The NgModule decorator has five important(among all) options
The imports option is used to import other dependent modules. The
BrowserModule is required by default for any web based angular application
The declarations option is used to define components in the respective module
The bootstrap option tells Angular which Component to bootstrap in the
application
The providers option is used to configure set of injectable objects that are
available in the injector of this module.
The entryComponents option is a set of components dynamically loaded into the
view.
What is a data binding?
Data binding is a core concept in Angular and allows to define communication
between a component and the DOM, making it very easy to define interactive
applications without worrying about pushing and pulling data. There are four
forms of data binding(divided as 3 categories) which differ in the way the data is
flowing.
From the Component to the DOM:
Interpolation: {{ value }}: Adds the value of a property from the component
<li>Name: {{ user.name }}</li>
<li>Address: {{ user.address }}</li>
Property binding: [property]=”value”: The value is passed from the
component to the specified property or simple HTML attribute
<input type="email" [value]="user.email">
From the DOM to the Component: Event binding:
(event)=”function”: When a specific DOM event happens (eg.: click, change,
keyup), call the specified method in the component
<button (click)="logout()"></button>
Two-way binding: Two-way data binding: [(ngModel)]=”value”: Two-way
data binding allows to have the data flow both ways. For example, in the below
code snippet, both the email DOM input and component email property are in
sync
<input type="email" [(ngModel)]="user.email">
What is metadata?
Metadata is used to decorate a class so that it can configure the expected
behavior of the class. The metadata is represented by decorators
Class decorators, e.g. @Component and @NgModule
import { NgModule, Component } from '@angular/core';
@Component({
selector: 'my-component',
template: '<div>Class decorator</div>',
})
export class MyComponent {
constructor() {
console.log('Hey I am a component!');
}
}
@NgModule({
imports: [],
declarations: [],
})
export class MyModule {
constructor() {
console.log('Hey I am a module!');
}
}
Property decorators Used for properties inside classes, e.g. @Input and
@Output
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-component',
template: '<div>Property decorator</div>'
})
export class MyComponent {
@Input()
title: string;
}
Method decorators Used for methods inside classes, e.g. @HostListener
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'my-component',
template: '<div>Method decorator</div>'
})
export class MyComponent {
@HostListener('click', ['$event'])
onHostClick(event: Event) {
// clicked, `event` available
}
}
Parameter decorators Used for parameters inside class constructors, e.g.
@Inject, Optional
import { Component, Inject } from '@angular/core';
import { MyService } from './my-service';
@Component({
selector: 'my-component',
template: '<div>Parameter decorator</div>'
})
export class MyComponent {
constructor(@Inject(MyService) myService) {
console.log(myService); // MyService
}
}
What is angular CLI?
Angular CLI(Command Line Interface) is a command line interface to scaffold
and build angular apps using nodejs style (commonJs) modules. You need to
install using below npm command,
npm install @angular/cli@latest
Below are the list of few commands, which will come handy while creating
angular projects
Creating New Project: ng new
Generating Components, Directives & Services: ng generate/g The different
types of commands would be,
ng generate class my-new-class: add a class to your application
ng generate component my-new-component: add a component to your
application
ng generate directive my-new-directive: add a directive to your application
ng generate enum my-new-enum: add an enum to your application
ng generate module my-new-module: add a module to your application
ng generate pipe my-new-pipe: add a pipe to your application
ng generate service my-new-service: add a service to your application
Running the Project: ng serve
What is the difference between constructor and ngOnInit?
TypeScript classes has a default method called constructor which is normally
used for the initialization purpose. Whereas ngOnInit method is specific to
Angular, especially used to define Angular bindings. Even though constructor
getting called first, it is preferred to move all of your Angular bindings to
ngOnInit method. In order to use ngOnInit, you need to implement OnInit
interface as below,
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first
ngOnChanges()
}
}
What is a service?
A service is used when a common functionality needs to be provided to various
modules. Services allow for greater separation of concerns for your application
and better modularity by allowing you to extract common functionality out of
components.
Let's create a repoService which can be used across components,
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({ // The Injectable decorator is required for dependency
injection to work
// providedIn option registers the service with a specific
NgModule
providedIn: 'root', // This declares the service with the root
app (AppModule)
})
export class RepoService{
constructor(private http: Http){
}
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
The above service uses Http service as a dependency.
What is dependency injection in Angular?
Dependency injection (DI), is an important application design pattern in which a
class asks for dependencies from external sources rather than creating them
itself. Angular comes with its own dependency injection framework for resolving
dependencies( services or objects that a class needs to perform its function).So
you can have your services depend on other services throughout your
application.
How is Dependency Hierarchy formed?
What is the purpose of async pipe?
The AsyncPipe subscribes to an observable or promise and returns the latest
value it has emitted. When a new value is emitted, the pipe marks the
component to be checked for changes.
Let's take a time observable which continuously updates the view for every 2
seconds with the current time.
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}
What is the option to choose between inline and external
template file?
You can store your component's template in one of two places. You can define it
inline using the template property, or you can define the template in a separate
HTML file and link to it in the component metadata using
the @Component decorator's templateUrl property.
The choice between inline and separate HTML is a matter of taste,
circumstances, and organization policy. But normally we use inline template for
small portion of code and external template file for bigger views. By default, the
Angular CLI generates components with a template file. But you can override
that with the below command,
ng generate component hero -it
⬆ Back to Top
What is the purpose of ngFor directive?
We use Angular ngFor directive in the template to display each item in the list.
For example, here we iterate over list of users,
<li *ngFor="let user of users">
{{ user }}
</li>
The user variable in the ngFor double-quoted instruction is a template input
variable
⬆ Back to Top
What is the purpose of ngIf directive?
Sometimes an app needs to display a view or a portion of a view only under
specific circumstances. The Angular ngIf directive inserts or removes an element
based on a truthy/falsy condition. Let's take an example to display a message if
the user age is more than 18,
<p *ngIf="user.age > 18">You are not eligible for student pass!</p>
Note: Angular isn't showing and hiding the message. It is adding and removing
the paragraph element from the DOM. That improves performance, especially in
the larger projects with many data bindings.
⬆ Back to Top
What happens if you use script tag inside template?
Angular recognizes the value as unsafe and automatically sanitizes it, which
removes the script tag but keeps safe content such as the text content of
the script tag. This way it eliminates the risk of script injection attacks. If you
still use it then it will be ignored and a warning appears in the browser console.
Let's take an example of innerHtml property binding which causes XSS
vulnerability,
export class InnerHtmlBindingComponent {
// For example, a user/attacker-controlled value from a URL.
htmlSnippet = 'Template <script>alert("0wned")</script>
<b>Syntax</b>';
}
What is interpolation?
Interpolation is a special syntax that Angular converts into property binding. It’s
a convenient alternative to property binding. It is represented by double curly
braces({{}}). The text between the braces is often the name of a component
property. Angular replaces that name with the string value of the corresponding
component property.
Let's take an example,
<h3>
{{title}}
<img src="{{url}}" style="height:30px">
</h3>
In the example above, Angular evaluates the title and url properties and fills in
the blanks, first displaying a bold application title and then a URL.
What are template expressions?
A template expression produces a value similar to any Javascript expression.
Angular executes the expression and assigns it to a property of a binding target;
the target might be an HTML element, a component, or a directive. In the
property binding, a template expression appears in quotes to the right of the =
symbol as in [property]="expression". In interpolation syntax, the template
expression is surrounded by double curly braces. For example, in the below
interpolation, the template expression is {{username}},
<h3>{{username}}, welcome to Angular</h3>
The below javascript expressions are prohibited in template expression
assignments (=, +=, -=, ...)
new
chaining expressions with ; or ,
increment and decrement operators (++ and --)
What are template statements?
A template statement responds to an event raised by a binding target such as an
element, component, or directive. The template statements appear in quotes to
the right of the = symbol like (event)="statement".
Let's take an example of button click event's statement
<button (click)="editProfile()">Edit Profile</button>
In the above expression, editProfile is a template statement. The below
JavaScript syntax expressions are not allowed.
new
increment and decrement operators, ++ and --
operator assignment, such as += and -=
the bitwise operators | and &
the template expression operators
How do you categorize data binding types?
Binding types can be grouped into three categories distinguished by the
direction of data flow. They are listed as below,
From the source-to-view
From view-to-source
View-to-source-to-view
The possible binding syntax can be tabularized as below,
Data direction Syntax Type
1. {{expression}} 2. Interpolation,
From the source-
[target]="expression" 3. bind- Property, Attribute,
to-view(One-way)
target="expression" Class, Style
From view-to- 1. (target)="statement" 2. on-
Event
source(One-way) target="statement"
View-to-source-to- 1. [(target)]="expression" 2. bindon-
Two-way
view(Two-way) target="expression"
What are pipes?
A pipe takes in data as input and transforms it to a desired output. For example,
let us take a pipe to transform a component's birthday property into a human-
friendly date using date pipe.
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18); // June 18, 1987
}
What is a parameterized pipe?
A pipe can accept any number of optional parameters to fine-tune its output. The
parameterized pipe can be created by declaring the pipe name with a colon ( : )
and then the parameter value. If the pipe accepts multiple parameters, separate
the values with colons. Let's take a birthday example with a particular
format(dd/MM/yyyy):
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday |
date:'dd/MM/yyyy'}}</p>` // 18/06/1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Note: The parameter value can be any valid template expression, such as a
string literal or a component property.
How do you chain pipes?
You can chain pipes together in potentially useful combinations as per the needs.
Let's take a birthday property which uses date pipe(along with parameter) and
uppercase pipes as below
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `<p>Birthday is {{ birthday | date:'fullDate' |
uppercase}} </p>` // THURSDAY, JUNE 18, 1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
What is a custom pipe?
Apart from built-inn pipes, you can write your own custom pipe with the below
key characteristics,
A pipe is a class decorated with pipe metadata @Pipe decorator, which you
import from the core Angular library For example,
@Pipe({name: 'myCustomPipe'})
The pipe class implements the PipeTransform interface's transform method
that accepts an input value followed by optional parameters and returns the
transformed value. The structure of pipeTransform would be as below,
interface PipeTransform {
transform(value: any, ...args: any[]): any
}
The @Pipe decorator allows you to define the pipe name that you'll use within
template expressions. It must be a valid JavaScript identifier.
template: `{{someInputValue | myCustomPipe: someOtherValue}}`
Give an example of custom pipe?
You can create custom reusable pipes for the transformation of existing value.
For example, let us create a custom pipe for finding file size based on an
extension,
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'customFileSizePipe'})
export class FileSizePipe implements PipeTransform {
transform(size: number, extension: string = 'MB'): string {
return (size / (1024 * 1024)).toFixed(2) + extension;
}
}
Now you can use the above pipe in template expression as below,
template: `
<h2>Find the size of a file</h2>
<p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
`
What is the difference between pure and impure pipe?
A pure pipe is only called when Angular detects a change in the value or the
parameters passed to a pipe. For example, any changes to a primitive input
value (String, Number, Boolean, Symbol) or a changed object reference (Date,
Array, Function, Object).
An impure pipe is called for every change detection cycle no matter whether the
value or parameters changes. i.e, An impure pipe is called often, as often as
every keystroke or mouse-move.
What is a bootstrapping module?
Every application has at least one Angular module, the root module that you
bootstrap to launch the application is called as bootstrapping module. It is
commonly known as AppModule. The default structure of AppModule generated
by AngularCLI would be as follows,
```javascript
/* JavaScript imports */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
/* the AppModule class with the @NgModule decorator */
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
What are observables?
Observables are declarative which provide support for passing messages
between publishers and subscribers in your application. They are mainly used for
event handling, asynchronous programming, and handling multiple values. In
this case, you define a function for publishing values, but it is not executed until
a consumer subscribes to it. The subscribed consumer then receives notifications
until the function completes, or until they unsubscribe.
What is HttpClient and its benefits?
Most of the Front-end applications communicate with backend services over
HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular
provides a simplified client HTTP API known as HttpClient which is based on top
of XMLHttpRequest interface. This client is avaialble
from @angular/common/http package. You can import in your root module as
below,
import { HttpClientModule } from '@angular/common/http';
The major advantages of HttpClient can be listed as below,
Contains testability features
Provides typed request and response objects
Intercept request and response
Supports Observable APIs
Supports streamlined error handling
Explain on how to use HttpClient with an example?
Below are the steps need to be followed for the usage of HttpClient.
Import HttpClient into root module:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
......
})
export class AppModule {}
Inject the HttpClient into the application: Let's create a
userProfileService(userprofile.service.ts) as an example. It also defines get
method of HttpClient
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
const userProfileUrl: string = 'assets/data/profile.json';
@Injectable()
export class UserProfileService {
constructor(private http: HttpClient) { }
getUserProfile() {
return this.http.get(this.userProfileUrl);
}
}
Create a component for subscribing service: Let's create a component called
UserProfileComponent(userprofile.component.ts) which inject UserProfileService
and invokes the service method,
fetchUserProfile() {
this.userProfileService.getUserProfile()
.subscribe((data: User) => this.user = {
id: data['userId'],
name: data['firstName'],
city: data['city']
});
}
Since the above service method returns an Observable which needs to be
subscribed in the component.
How can you read full response?
The response body doesn't may not return full response data because
sometimes servers also return special headers or status code which are
important for the application workflow. Inorder to get full response, you should
use observe option from HttpClient,
getUserResponse(): Observable<HttpResponse<User>> {
return this.http.get<User>(
this.userUrl, { observe: 'response' });
}
Now HttpClient.get() method returns an Observable of typed HttpResponse
rather than just the JSON data.
How do you perform Error handling?
If the request fails on the server or failed to reach the server due to network
issues then HttpClient will return an error object instead of a successful reponse.
In this case, you need to handle in the component by passing error object as a
second callback to subscribe() method.
Let's see how it can be handled in the component with an example,
fetchUser() {
this.userService.getProfile()
.subscribe(
(data: User) => this.userProfile = { ...data }, // success
path
error => this.error = error // error path
);
}
It is always a good idea to give the user some meaningful feedback instead of
displaying the raw error object returned from HttpClient.
What is RxJS?
RxJS is a library for composing asynchronous and callback-based code in a
functional, reactive style using Observables. Many APIs such as HttpClient
produce and consume RxJS Observables and also uses operators for processing
observables.
For example, you can import observables and operators for using HttpClient as
below,
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
What is subscribing?
An Observable instance begins publishing values only when someone subscribes
to it. So you need to subscribe by calling the subscribe() method of the
instance, passing an observer object to receive the notifications.
Let's take an example of creating and subscribing to a simple observable, with
an observer that logs the received message to the console.
Creates an observable sequence of 5 integers, starting from 1
const source = range(1, 5);
// Create observer object
const myObserver = {
next: x => console.log('Observer got a next value: ' + x),
error: err => console.error('Observer got an error: ' + err),
complete: () => console.log('Observer got a complete
notification'),
};
// Execute with the observer object and Prints out each item
source.subscribe(myObserver);
// => Observer got a next value: 1
// => Observer got a next value: 2
// => Observer got a next value: 3
// => Observer got a next value: 4
// => Observer got a next value: 5
// => Observer got a complete notification
What is an observable?
An Observable is a unique Object similar to a Promise that can help manage
async code. Observables are not part of the JavaScript language so we need to
rely on a popular Observable library called RxJS. The observables are created
using new keyword.
Let see the simple example of observable,
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
What is an observer?
Observer is an interface for a consumer of push-based notifications delivered by
an Observable. It has below structure,
interface Observer<T> {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
A handler that implements the Observer interface for receiving observable
notifications will be passed as a parameter for observable as below,
myObservable.subscribe(myObserver);
Note: If you don't supply a handler for a notification type, the observer ignores
notifications of that type.
What is the difference between promise and observable?
Below are the list of differences between promise and observable,
Observable Promise
Declarative: Computation does not start until subscription so Execute immediately
that they can be run whenever you need the result on creation
Provide multiple values over time Provide only one
Subscribe method is used for error handling which makes Push errors to the
centralized and predictable error handling child promises
Provides chaining and subscription to handle complex Uses only .then()
applications clause
What is multicasting?
Multi-casting is the practice of broadcasting to a list of multiple subscribers in a
single execution.
Let's demonstrate the multi-casting feature,
var source = Rx.Observable.from([1, 2, 3]);
var subject = new Rx.Subject();
var multicasted = source.multicast(subject);
// These are, under the hood, `subject.subscribe({...})`:
multicasted.subscribe({
next: (v) => console.log('observerA: ' + v)
});
multicasted.subscribe({
next: (v) => console.log('observerB: ' + v)
});
// This is, under the hood, `s
How do you perform error handling in observables?
You can handle errors by specifying an error callback on the observer instead
of relying on try/catch which are ineffective in asynchronous environment.
For example, you can define error callback as below,
myObservable.subscribe({
next(num) { console.log('Next num: ' + num)},
error(err) { console.log('Received an errror: ' + err)}
});
What is the short hand notation for subscribe method?
The subscribe() method can accept callback function definitions in line, for next,
error, and complete handlers is known as short hand notation or Subscribe
method with positional arguments.
For example, you can define subscribe method as below,
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
What are the utility functions provided by RxJS?
The RxJS library also provides below utility functions for creating and working
with observables.
Converting existing code for async operations into observables
Iterating through the values in a stream
Mapping values to different types
Filtering streams
Composing multiple streams
What are observable creation functions?
RxJS provides creation functions for the process of creating observables from
things such as promises, events, timers and Ajax requests. Let us explain each of
them with an example,
Create an observable from a promise
import { from } from 'rxjs'; // from function
const data = from(fetch('/api/endpoint')); //Created from Promise
data.subscribe({
next(response) { console.log(response); },
error(err) { console.error('Error: ' + err); },
complete() { console.log('Completed'); }
});
Create an observable that creates an AJAX request
import { ajax } from 'rxjs/ajax'; // ajax function
const apiData = ajax('/api/data'); // Created from AJAX request
// Subscribe to create the request
apiData.subscribe(res => console.log(res.status, res.response));
Create an observable from a counter
import { interval } from 'rxjs'; // interval function
const secondsCounter = interval(1000); // Created from Counter value
secondsCounter.subscribe(n =>
console.log(`Counter value: ${n}`));
Create an observable from an event
import { fromEvent } from 'rxjs';
const el = document.getElementById('custom-element');
const mouseMoves = fromEvent(el, 'mousemove');
const subscription = mouseMoves.subscribe((e: MouseEvent) => {
console.log(`Coordnitaes of mouse pointer: ${e.clientX} * $
{e.clientY}`);
});
⬆ Back to Top
What will happen if you do not supply handler for observer?
Normally an observer object can define any combination of next, error and
complete notification type handlers. If you don't supply a handler for a
notification type, the observer just ignores notifications of that type.
What are angular elements?
Angular elements are Angular components packaged as custom elements(a
web standard for defining new HTML elements in a framework-agnostic way).
Angular Elements hosts an Angular component, providing a bridge between the
data and logic defined in the component and standard DOM APIs, thus, providing
a way to use Angular components in non-Angular environments.
What is the browser support of Angular Elements?
Since Angular elements are packaged as custom elements the browser support
of angular elements is same as custom elements support.
This feature is is currently supported natively in a number of browsers and
pending for other browsers.
Browser Angular Element Support
Chrome Natively supported
Opera Natively supported
Safari Natively supported
Natively supported from 63 version onwards. You need to enable
Firefox dom.webcomponents.enabled and
dom.webcomponents.customelements.enabled in older browsers
Browser Angular Element Support
Edge Currently it is in progress
What are custom elements?
Custom elements (or Web Components) are a Web Platform feature which
extends HTML by allowing you to define a tag whose content is created and
controlled by JavaScript code. The browser maintains a CustomElementRegistry of
defined custom elements, which maps an instantiable JavaScript class to an
HTML tag. Currently this feature is supported by Chrome, Firefox, Opera, and
Safari, and available in other browsers through polyfills.
Do I need to bootstrap custom elements?
No, custom elements bootstrap (or start) automatically when they are added to
the DOM, and are automatically destroyed when removed from the DOM. Once a
custom element is added to the DOM for any page, it looks and behaves like any
other HTML element, and does not require any special knowledge of Angular.
Explain how custom elements works internally?
Below are the steps in an order about custom elements functionality,
App registers custom element with browser: Use
the createCustomElement() function to convert a component into a class that can
be registered with the browser as a custom element.
App adds custom element to DOM: Add custom element just like a built-in
HTML element directly into the DOM.
Browser instantiate component based class: Browser creates an instance of
the registered class and adds it to the DOM.
Instance provides content with data binding and change detection: The
content with in template is rendered using the component and DOM data. The
flow chart of the custom elements functionality would be as follows,
⬆ Back to Top
How to transfer components to custom elements?
Transforming components to custom elements involves two major steps,
Build custom element class: Angular provides
the createCustomElement() function for converting an Angular component (along
with its dependencies) to a custom element. The conversion process
implements NgElementConstructor interface, and creates a constructor class
which is used to produce a self-bootstrapping instance of Angular component.
Register element class with browser: It uses customElements.define() JS
function, to register the configured constructor and its associated custom-
element tag with the browser's CustomElementRegistry. When the browser
encounters the tag for the registered element, it uses the constructor to create a
custom-element instance.
The detailed structure would be as
follows,
⬆ Back to Top
What are the mapping rules between Angular component
and custom element?
The Component properties and logic maps directly into HTML attributes and the
browser's event system. Let us describe them in two steps,
The createCustomElement() API parses the component input properties with
corresponding attributes for the custom element. For example, component
@Input('myInputProp') converted as custom element attribute my-input-prop.
The Component outputs are dispatched as HTML Custom Events, with the name
of the custom event matching the output name. For example, component
@Output() valueChanged = new EventEmitter() converted as custom element
with dispatch event as "valueChanged".
⬆ Back to Top
How do you define typings for custom elements?
You can use the NgElement and WithProperties types exported from
@angular/elements.
Let's see how it can be applied by comparing with Angular component.
The simple container with input property would be as below,
@Component(...)
class MyContainer {
@Input() message: string;
}
After applying types typescript validates input value and their types,
const container = document.createElement('my-container') as NgElement &
WithProperties<{message: string}>;
container.message = 'Welcome to Angular elements!';
container.message = true; // <-- ERROR: TypeScript knows this should be a
string.
container.greet = 'News'; // <-- ERROR: TypeScript knows there is no
`greet` property on `container`.
What are dynamic components?
Dynamic components are the components in which components location in the
application is not defined at build time.i.e, They are not used in any angular
template. But the component is instantiated and placed in the application at
runtime.
What are the various kinds of directives?
There are mainly three kinds of directives,
Components — These are directives with a template.
Structural directives — These directives change the DOM layout by adding
and removing DOM elements.
Attribute directives — These directives change the appearance or behavior of
an element, component, or another directive.
How do you create directives using CLI?
You can use CLI command ng generate directive to create the directive class
file. It creates the source file(src/app/components/directivename.directive.ts),
the respective test file(.spec.ts) and declare the directive class file in root
module.
Give an example for attribute directives?
Let's take simple highlighter behavior as a example directive for DOM element.
You can create and apply the attribute directive using below steps,
Create HighlightDirective class with the file
name src/app/highlight.directive.ts. In this file, we need to
import Directive from core library to apply the metadata and ElementRef in
the directive's constructor to inject a reference to the host DOM element ,
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
Apply the attribute directive as an attribute to the host element(for example,
)
<p appHighlight>Highlight me!</p>
Run the application to see the highlight behavior on paragraph element
ng serve
What is Angular Router?
Angular Router is a mechanism in which navigation happens from one view to
the next as users perform application tasks. It borrows the concepts or model of
browser's application navigation.
What is the purpose of base href tag?
The routing application should add element to the index.html as the first child in
the tag in order to indicate how to compose navigation URLs. If app folder is the
application root then you can set the href value as below
<base href="/">
What are the router imports?
The Angular Router which represents a particular component view for a given
URL is not part of Angular Core. It is available in library
named @angular/router to import required router components. For example, we
import them in app module as below,
import { RouterModule, Routes } from '@angular/router';
What is router outlet?
The RouterOutlet is a directive from the router library and it acts as a
placeholder that marks the spot in the template where the router should display
the components for that outlet. Router outlet is used like a component,
<router-outlet></router-outlet>
<!-- Routed components go here -->
What are router links?
The RouterLink is a directive on the anchor tags give the router control over
those elements. Since the navigation paths are fixed, you can assign string
values to router-link directive as below,
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
What are active router links?
RouterLinkActive is a directive that toggles css classes for active RouterLink
bindings based on the current RouterState. i.e, the Router will add CSS classes
when this link is active and and remove when the link is inactive. For example,
you can add them to RouterLinks as below
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of
todos</a>
<a routerLink="/completed" routerLinkActive="active">Completed
todos</a>
</nav>
<router-outlet></router-outlet>
What is router state?
RouterState is a tree of activated routes. Every node in this tree knows about the
"consumed" URL segments, the extracted parameters, and the resolved data.
You can access the current RouterState from anywhere in the application using
the Router service and the routerState property.
@Component({templateUrl:'template.html'})
class MyComponent {
constructor(router: Router) {
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
const id: Observable<string> = child.params.map(p => p.id);
//...
}
}
What are router events?
During each navigation, the Router emits navigation events through the
Router.events property allowing you to track the lifecycle of the route.
The sequence of router events is as below,
NavigationStart,
RouteConfigLoadStart,
RouteConfigLoadEnd,
RoutesRecognized,
GuardsCheckStart,
ChildActivationStart,
ActivationStart,
GuardsCheckEnd,
ResolveStart,
ResolveEnd,
ActivationEnd
ChildActivationEnd
NavigationEnd,
NavigationCancel,
NavigationError
Scroll
What is activated route?
ActivatedRoute contains the information about a route associated with a
component loaded in an outlet. It can also be used to traverse the router state
tree. The ActivatedRoute will be injected as a router service to access the
information. In the below example, you can access route path and parameters,
@Component({...})
class MyComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map(p =>
p.id));
const url: Observable<string> = route.url.pipe(map(segments =>
segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map(d => d.user));
}
}
How do you define routes?
A router must be configured with a list of route definitions. You configures the
router with routes via the RouterModule.forRoot() method, and adds the result to
the AppModule's imports array.
const appRoutes: Routes = [
{ path: 'todo/:id', component: TodoDetailComponent },
{
path: 'todos',
component: TodosListComponent,
data: { title: 'Todos List' }
},
{ path: '',
redirectTo: '/todos',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
What is the purpose of Wildcard route?
If the URL doesn't match any predefined routes then it causes the router to throw
an error and crash the app. In this case, you can use wildcard route. A wildcard
route has a path consisting of two asterisks to match every URL.
For example, you can define PageNotFoundComponent for wildcard route as
below
{ path: '**', component: PageNotFoundComponent }
⬆ Back to Top
Do I need a Routing Module always?
No, the Routing Module is a design choice. You can skip routing Module (for
example, AppRoutingModule) when the configuration is simple and merge the
routing configuration directly into the companion module (for example,
AppModule). But it is recommended when the configuration is complex and
includes specialized guard and resolver services.
⬆ Back to Top
What is Angular Universal?
Angular Universal is a server-side rendering module for Angular applications in
various scenarios. This is a community driven project and available under
@angular/platform-server package. Recently Angular Universal is integrated with
Angular CLI.
What are different types of compilation in Angular?
Angular offers two ways to compile your application,
Just-in-Time (JIT)
Ahead-of-Time (AOT)
What is JIT?
Just-in-Time (JIT) is a type of compilation that compiles your app in the browser
at runtime. JIT compilation is the default when you run the ng build (build only) or
ng serve (build and serve locally) CLI commands. i.e, the below commands used
for JIT compilation,
ng build
ng serve
What is AOT?
Ahead-of-Time (AOT) is a type of compilation that compiles your app at build
time. For AOT compilation, include the --aot option with the ng build or ng serve
command as below,
ng build --aot
ng serve --aot
Note: The ng build command with the --prod meta-flag ( ng build --prod)
compiles with AOT by default.
Why do we need compilation process?
The Angular components and templates cannot be understood by the browser
directly. Due to that Angular applications require a compilation process before
they can run in a browser. For example, In AOT compilation, both Angular HTML
and TypeScript code converted into efficient JavaScript code during the build
phase before browser runs it.
What are the advantages with AOT?
Below are the list of AOT benefits,
Faster rendering: The browser downloads a pre-compiled version of the
application. So it can render the application immediately without compiling the
app.
Fewer asynchronous requests: It inlines external HTML templates and CSS
style sheets within the application javascript which eliminates separate ajax
requests.
Smaller Angular framework download size: Doesn't require downloading the
Angular compiler. Hence it dramatically reduces the application payload.
Detect template errors earlier: Detects and reports template binding errors
during the build step itself
Better security: It compiles HTML templates and components into JavaScript.
So there won't be any injection attacks.
What are the ways to control AOT compilation?
You can control your app compilation in two ways,
By providing template compiler options in the tsconfig.json file
By configuring Angular metadata with decorators
What are the restrictions of metadata?
In Angular, You must write metadata with the following general constraints,
Write expression syntax with in the supported range of javascript features
The compiler can only reference symbols which are exported
Only call the functions supported by the compiler
Decorated and data-bound class members must be public.
What are the three phases of AOT?
The AOT compiler works in three phases,
Code Analysis: The compiler records a representation of the source
Code generation: It handles the interpretation as well as places restrictions on
what it interprets.
Validation: In this phase, the Angular template compiler uses the TypeScript
compiler to validate the binding expressions in templates.
Can I use arrow functions in AOT?
No, Arrow functions or lambda functions can’t be used to assign values to the
decorator properties. For example, the following snippet is invalid:
@Component({
providers: [{
provide: MyService, useFactory: () => getService()
}]
})
To fix this, it has to be changed as following exported function:
function getService(){
return new MyService();
}
@Component({
providers: [{
provide: MyService, useFactory: getService
}]
})
If you still use arrow function, it generates an error node in place of the function.
When the compiler later interprets this node, it reports an error to turn the arrow
function into an exported function. Note: From Angular5 onwards, the compiler
automatically performs this rewriting while emitting the .js file.
What is the purpose of metadata json files?
The metadata.json file can be treated as a diagram of the overall structure of a
decorator's metadata, represented as an abstract syntax tree(AST). During the
analysis phase, the AOT collector scan the metadata recorded in the Angular
decorators and outputs metadata information in .metadata.json files, one
per .d.ts file.
Can I use any javascript feature for expression syntax in
AOT?
No, the AOT collector understands a subset of (or limited) JavaScript features. If
an expression uses unsupported syntax, the collector writes an error node to
the .metadata.json file. Later point of time, the compiler reports an error if it
needs that piece of metadata to generate the application code.
What is folding?
The compiler can only resolve references to exported symbols in the metadata.
Where as some of the non-exported members are folded while generating the
code. i.e Folding is a process in which the collector evaluate an expression
during collection and record the result in the .metadata.json instead of the
original expression. For example, the compiler couldn't refer selector reference
because it is not exported
let selector = 'app-root';
@Component({
selector: selector
})
Will be folded into inline selector
@Component({
selector: 'app-root'
})
Remember that the compiler can’t fold everything. For example, spread operator
on arrays, objects created using new keywords and function calls.
What are macros?
The AOT compiler supports macros in the form of functions or static methods
that return an expression in a single return expression. For example, let us
take a below macro function,
export function wrapInArray<T>(value: T): T[] {
return [value];
}
You can use it inside metadata as an expression,
@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
The compiler treats the macro expression as it written directly
@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}
Give an example of few metadata errors?
Below are some of the errors encountered in metadata,
Expression form not supported: Some of the language features outside of the
compiler's restricted expression syntax used in angular metadata can produce
this error. Let's see some of these examples,
1. export class User { ... }
const prop = typeof User; // typeof is not valid in metadata
2. { provide: 'token', useValue: { [prop]: 'value' } }; // bracket
notation is not valid in metadata
Reference to a local (non-exported) symbol: The compiler encountered a
referenced to a locally defined symbol that either wasn't exported or wasn't
initialized. Let's take example of this error,
// ERROR
let username: string; // neither exported nor initialized
@Component({
selector: 'my-component',
template: ... ,
providers: [
{ provide: User, useValue: username }
]
})
export class MyComponent {}
You can fix this by either exporting or initializing the value,
export let username: string; // exported
(or)
let username = 'John'; // initialized
Function calls are not supported: The compiler does not currently support
function expressions or lambda functions. For example, you cannot set a
provider's useFactory to an anonymous function or arrow function as below.
providers: [
{ provide: MyStrategy, useFactory: function() { ... } },
{ provide: OtherStrategy, useFactory: () => { ... } }
]
You can fix this with exported function
export function myStrategy() { ... }
export function otherStrategy() { ... }
... // metadata
providers: [
{ provide: MyStrategy, useFactory: myStrategy },
{ provide: OtherStrategy, useFactory: otherStrategy },
Destructured variable or constant not supported: The compiler does not
support references to variables assigned by destructuring. For example, you
cannot write something like this:
import { user } from './user';
// destructured assignment to name and age
const {name, age} = user;
... //metadata
providers: [
{provide: Name, useValue: name},
{provide: Age, useValue: age},
]
You can fix this by non-destructured values
import { user } from './user';
... //metadata
providers: [
{provide: Name, useValue: user.name},
{provide: Age, useValue: user.age},
]
What is metadata rewriting?
Metadata rewriting is the process in which the compiler converts the expression
initializing the fields such as useClass, useValue, useFactory, and data into an
exported variable, which replaces the expression. Remember that the compiler
does this rewriting during the emit of the .js file but not in definition files( .d.ts
file).
How do you provide configuration inheritance?
Angular Compiler supports configuration inheritance through extends in the
tsconfig.json on angularCompilerOptions. i.e, The configuration from the base
file(for example, tsconfig.base.json) are loaded first, then overridden by those in
the inheriting config file.
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
How do you specify angular template compiler options?
The angular template compiler options are specified as members of
the angularCompilerOptions object in the tsconfig.json file. These options will
be specified adjecent to typescript compiler options.
{
"compilerOptions": {
"experimentalDecorators": true,
...
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"preserveWhitespaces": true,
...
}
}
How do you enable binding expression validation?
You can enable binding expression validation explicitly by adding the compiler
option fullTemplateTypeCheck in the "angularCompilerOptions" of the
project's tsconfig.json. It produces error messages when a type error is detected
in a template binding expression.
For example, consider the following component:
@Component({
selector: 'my-component',
template: '{{user.contacts.email}}'
})
class MyComponent {
user?: User;
}
This will produce the following error:
my.component.ts.MyComponent.html(1,1): : Property 'contacts' does
not exist on type 'User'. Did you mean 'contact'?
What is the purpose of any type cast function?
You can disable binding expression type checking using $any() type cast
function(by surrounding the expression). In the following example, the error
Property contacts does not exist is suppressed by casting user to the any type.
template:
'{{ $any(user).contacts.email }}'
The $any() cast function also works with this to allow access to undeclared
members of the component.
template:
'{{ $any(this).contacts.email }}'
What is Non null type assertion operator?
You can use the non-null type assertion operator to suppress the Object is
possibly 'undefined' error. In the following example, the user and contact
properties are always set together, implying that contact is always non-null if
user is non-null. The error is suppressed in the example by using contact!.email.
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.name}} contacted through
{{contact!.email}} </span>'
})
class MyComponent {
user?: User;
contact?: Contact;
setData(user: User, contact: Contact) {
this.user = user;
this.contact = contact;
}
}
What is type narrowing?
The expression used in an ngIf directive is used to narrow type unions in the
Angular template compiler similar to if expression in typescript. So *ngIf allows
the typeScript compiler to infer that the data used in the binding expression will
never be undefined.
@Component({
selector: 'my-component',
template: '<span *ngIf="user"> {{user.contact.email}} </span>'
})
class MyComponent {
user?: User;
}
How do you describe various dependencies in angular
application?
The dependencies section of package.json with in an angular application can be
divided as follow,
Angular packages: Angular core and optional modules; their package names
begin @angular/.
Support packages: Third-party libraries that must be present for Angular apps
to run.
Polyfill packages: Polyfills plug gaps in a browser's JavaScript implementation.
What is zone?
A Zone is an execution context that persists across async tasks. Angular relies on
zone.js to run Angular's change detection processes when native JavaScript
operations raise events
What is the purpose of common module?
The commonly-needed services, pipes, and directives provided by
@angular/common module. Apart from these HttpClientModule is available under
@angular/common/http.
What is codelyzer?
Codelyzer provides set of tslint rules for static code analysis of Angular
TypeScript projects. ou can run the static code analyzer over web apps,
NativeScript, Ionic etc. Angular CLI has support for this and it can be use as
below,
ng new codelyzer
ng lint
What is angular animation?
Angular's animation system is built on CSS functionality in order to animate any
property that the browser considers animatable. These properties includes
positions, sizes, transforms, colors, borders etc. The Angular modules for
animations are @angular/animations and @angular/platform-browser and
these dependencies are automatically added to your project when you create a
project using Angular CLI.
What are the steps to use animation module?
You need to follow below steps to implement animation in your angular project,
Enabling the animations module: Import BrowserAnimationsModule to add
animation capabilities into your Angular root application module(for example,
src/app/app.module.ts).
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from
'@angular/platform-browser/animations';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule
],
declarations: [ ],
bootstrap: [ ]
})
export class AppModule { }
Importing animation functions into component files: Import required
animation functions from @angular/animations in component files(for example,
src/app/app.component.ts).
import {
trigger,
state,
style,
animate,
transition,
// ...
} from '@angular/animations';
Adding the animation metadata property: add a metadata property called
animations: within the @Component() decorator in component files(for example,
src/app/app.component.ts)
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
animations: [
// animation triggers go here
]
})
What is State function?
Angular's state() function is used to define different states to call at the end of
each transition. This function takes two arguments: a unique name like open or
closed and a style() function.
For example, you can write a open state function
state('open', style({
height: '300px',
opacity: 0.5,
backgroundColor: 'blue'
})),
What is Style function?
The style function is used to define a set of styles to associate with a given state
name. You need to use it along with state() function to set CSS style attributes.
For example, in the close state, the button has a height of 100 pixels, an opacity
of 0.8, and a background color of green.
state('close', style({
height: '100px',
opacity: 0.8,
backgroundColor: 'green'
})),
Note: The style attributes must be in camelCase.
What is the purpose of animate function?
Angular Animations are a powerful way to implement sophisticated and
compelling animations for your Angular single page web application.
import { Component, OnInit, Input } from '@angular/core';
import { trigger, state, style, animate, transition } from
'@angular/animations';
@Component({
selector: 'app-animate',
templateUrl: `<div [@changeState]="currentState" class="myblock mx-
auto"></div>`,
styleUrls: `.myblock {
background-color: green;
width: 300px;
height: 250px;
border-radius: 5px;
margin: 5rem;
}`,
animations: [
trigger('changeState', [
state('state1', style({
backgroundColor: 'green',
transform: 'scale(1)'
})),
state('state2', style({
backgroundColor: 'red',
transform: 'scale(1.5)'
})),
transition('*=>state1', animate('300ms')),
transition('*=>state2', animate('2000ms'))
])
]
})
export class AnimateComponent implements OnInit {
@Input() currentState;
constructor() { }
ngOnInit() {
}
}
What is transition function?
The animation transition function is used to specify the changes that occur
between one state and another over a period of time. It accepts two arguments:
the first argument accepts an expression that defines the direction between two
transition states, and the second argument accepts an animate() function.
Let's take an example state transition from open to closed with an half second
transition between states.
transition('open => closed', [
animate('500ms')
]),
How to inject the dynamic script in angular?
Using DomSanitizer we can inject the dynamic Html,Style,Script,Url.
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'my-app',
template: `
<div [innerHtml]="htmlSnippet"></div>
`,
})
export class App {
constructor(protected sanitizer: DomSanitizer) {}
htmlSnippet: string =
this.sanitizer.bypassSecurityTrustScript("<script>safeCode()</script>");
}
What is a service worker and its role in Angular?
A service worker is a script that runs in the web browser and manages caching
for an application. Starting from 5.0.0 version, Angular ships with a service
worker implementation. Angular service worker is designed to optimize the end
user experience of using an application over a slow or unreliable network
connection, while also minimizing the risks of serving outdated content.
What are the design goals of service workers?
Below are the list of design goals of Angular's service workers,
It caches an application just like installing a native application
A running application continues to run with the same version of all files without
any incompatible files
When you refresh the application, it loads the latest fully cached version
When changes are published then it immediately updates in the background
Service workers saves the bandwidth by downloading the resources only when
they changed.
What are the differences between AngularJS and Angular
with respect to dependency injection?
Dependency injection is a common component in both AngularJS and Angular,
but there are some key differences between the two frameworks in how it
actually works.
AngularJS Angular
Dependency injection tokens are Tokens can have different types. They are often
always strings classes and sometimes can be strings.
There is exactly one injector even There is a tree hierarchy of injectors, with a
though it is a multi-module root injector and an additional injector for each
applications component.
What is Angular Ivy?
Angular Ivy is a new rendering engine for Angular. You can choose to opt in a
preview version of Ivy from Angular version 8.
You can enable ivy in a new project by using the --enable-ivy flag with the ng
new command
ng new ivy-demo-app --enable-ivy
You can add it to an existing project by adding enableIvy option in
the angularCompilerOptions in your project's tsconfig.app.json.
{
"compilerOptions": { ... },
"angularCompilerOptions": {
"enableIvy": true
}
}
What are the features included in ivy preview?
You can expect below features with Ivy preview,
Generated code that is easier to read and debug at runtime
Faster re-build time
Improved payload size
Improved template type checking
Can I use AOT compilation with Ivy?
Yes, it is a recommended configuration. Also, AOT compilation with Ivy is faster.
So you need set the default build options(with in angular.json) for your project to
always use AOT compilation.
{
"projects": {
"my-project": {
"architect": {
"build": {
"options": {
...
"aot": true,
}
}
}
}
}
}
What is Angular Language Service?
The Angular Language Service is a way to get completions, errors, hints, and
navigation inside your Angular templates whether they are external in an HTML
file or embedded in annotations/decorators in a string. It has the ability to
autodetect that you are opening an Angular file, reads your tsconfig.json file,
finds all the templates you have in your application, and then provides all the
language services.
How do you install angular language service in the project?
You can install Angular Language Service in your project with the following npm
command,
npm install --save-dev @angular/language-service
After that add the following to the "compilerOptions" section of your project's
tsconfig.json
"plugins": [
{"name": "@angular/language-service"}
]
Note: The completion and diagnostic services works for .ts files only. You need
to use custom plugins for supporting HTML files.
.
Is there any editor support for Angular Language Service?
Yes, Angular Language Service is currently available for Visual Studio Code and
WebStorm IDEs. You need to install angular language service using an extension
and devDependency respectively. In sublime editor, you need to install
typescript which has a language service plugin model.
Explain the features provided by Angular Language
Service?
Basically there are 3 main features provided by Angular Language Service,
Autocompletion: Autocompletion can speed up your development time by
providing you with contextual possibilities and hints as you type with in an
interpolation and elements.
Error checking: It can also warn you of mistakes in your code.
Navigation: Navigation allows you to hover a component, directive, module and
then click and press F12 to go directly to its definition.
How do you add web workers in your application?
You can add web worker anywhere in your application. For example, If the file
that contains your expensive computation is src/app/app.component.ts, you can
add a Web Worker using ng generate web-worker app command which will
create src/app/app.worker.ts web worker file. This command will perform below
actions,
Configure your project to use Web Workers
Adds app.worker.ts to receive messages
addEventListener('message', ({ data }) => {
const response = `worker response to ${data}`;
postMessage(response);
});
The component app.component.ts file updated with web worker file
if (typeof Worker !== 'undefined') {
// Create a new
const worker = new Worker('./app.worker', { type: 'module' });
worker.onmessage = ({ data }) => {
console.log('page got message: $\{data\}');
};
worker.postMessage('hello');
} else {
// Web Workers are not supported in this environment.
}
Note: You may need to refactor your initial scaffolding web worker code for
sending messages to and from.
What are the limitations with web workers?
You need to remember two important things when using Web Workers in Angular
projects,
Some environments or platforms(like @angular/platform-server) used in Server-
side Rendering, don't support Web Workers. In this case you need to provide a
fallback mechanism to perform the computations to work in this environments.
Running Angular in web worker using @angular/platform-webworker is not yet
supported in Angular CLI.
What is Angular CLI Builder?
In Angular8, the CLI Builder API is stable and available to developers who want to
customize the Angular CLI by adding or modifying commands. For example, you
could supply a builder to perform an entirely new task, or to change which third-
party tool is used by an existing command.
What is a builder?
A builder function is a function that uses the Architect API to perform a complex
process such as "build" or "test". The builder code is defined in an npm package.
For example, BrowserBuilder runs a webpack build for a browser target and
KarmaBuilder starts the Karma server and runs a webpack build for unit tests.
How do you invoke a builder?
The Angular CLI command ng run is used to invoke a builder with a specific
target configuration. The workspace configuration file, angular.json, contains
default configurations for built-in builders.
How do you create app shell in Angular?
An App shell is a way to render a portion of your application via a route at build
time. This is useful to first paint of your application that appears quickly because
the browser can render static HTML and CSS without the need to initialize
JavaScript. You can achieve this using Angular CLI which generates an app shell
for running server-side of your app.
ng generate appShell [options] (or)
ng g appShell [options]
What are the case types in Angular?
Angular uses capitalization conventions to distinguish the names of various
types. Angular follows the list of the below case types.
camelCase : Symbols, properties, methods, pipe names, non-component
directive selectors, constants uses lowercase on the first letter of the item. For
example, "selectedUser"
UpperCamelCase (or PascalCase): Class names, including classes that define
components, interfaces, NgModules, directives, and pipes uses uppercase on the
first letter of the item.
dash-case (or "kebab-case"): The descriptive part of file names, component
selectors uses dashes between the words. For example, "app-user-list".
UPPER_UNDERSCORE_CASE: All constants uses capital letters connected with
underscores. For example, "NUMBER_OF_USERS".
What are the class decorators in Angular?
A class decorator is a decorator that appears immediately before a class
definition, which declares the class to be of the given type, and provides
metadata suitable to the type
The following list of decorators comes under class decorators,
@Component()
@Directive()
@Pipe()
@Injectable()
@NgModule()
What are class field decorators?
The class field decorators are the statements declared immediately before a field
in a class definition that defines the type of that field. Some of the examples are:
@input and @output,
@Input() myProperty;
@Output() myEvent = new EventEmitter();
What is declarable in Angular?
Declarable is a class type that you can add to the declarations list of an
NgModule. The class types such as components, directives, and pipes comes can
be declared in the module. The structure of declarations would be,
declarations: [
YourComponent,
YourPipe,
YourDirective
],
What are the restrictions on declarable classes?
Below classes shouldn't be declared,
A class that's already declared in another NgModule
Ngmodule classes
Service classes
Helper classes
What is a DI token?
A DI token is a lookup token associated with a dependency provider in
dependency injection system. The injector maintains an internal token-provider
map that it references when asked for a dependency and the DI token is the key
to the map. Let's take example of DI Token usage,
const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector =
Injector.create({providers: [{provide: BASE_URL, useValue:
'http://some-domain.com'}]});
const url = injector.get(BASE_URL);
What is Angular DSL?
A domain-specific language (DSL) is a computer language specialized to a
particular application domain. Angular has its own Domain Specific Language
(DSL) which allows us to write Angular specific html-like syntax on top of normal
html. It has its own compiler that compiles this syntax to html that the browser
can understand. This DSL is defined in NgModules such as animations, forms,
and routing and navigation.
Basically you will see 3 main syntax in Angular DSL.
(): Used for Output and DOM events.
[]: Used for Input and specific DOM element attributes.
*: Structural directives(*ngFor or *ngIf) will affect/change the DOM structure.
.
what is an rxjs subject in Angular
An RxJS Subject is a special type of Observable that allows values to be
multicasted to many Observers. While plain Observables are unicast (each
subscribed Observer owns an independent execution of the Observable),
Subjects are multicast.
A Subject is like an Observable, but can multicast to many Observers. Subjects
are like EventEmitters: they maintain a registry of many listeners.
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
subject.next(2);
What is Bazel tool?
Bazel is a powerful build tool developed and massively used by Google and it can
keep track of the dependencies between different packages and build targets. In
Angular8, you can build your CLI application with Bazel. Note: The Angular
framework itself is built with Bazel.
What are the advantages of Bazel tool?
Below are the list of key advantages of Bazel tool,
It creates the possibility of building your back-ends and front-ends with the same
tool
The incremental build and tests
It creates the possibility to have remote builds and cache on a build farm.
How do you use Bazel with Angular CLI?
The @angular/bazel package provides a builder that allows Angular CLI to use
Bazel as the build tool.
Use in an existing applciation: Add @angular/bazel using CLI
ng add @angular/bazel
Use in a new application: Install the package and create the application with
collection option
npm install -g @angular/bazel
ng new --collection=@angular/bazel
When you use ng build and ng serve commands, Bazel is used behind the scenes
and outputs the results in dist/bin folder.
How do you run Bazel directly?
Sometimes you may want to bypass the Angular CLI builder and run Bazel
directly using Bazel CLI. You can install it globally using @bazel/bazel npm
package. i.e, Bazel CLI is available under @bazel/bazel package. After you can
apply the below common commands,
bazel build [targets] // Compile the default output artifacts of the given
targets.
bazel test [targets] // Run the tests with *_test targets found in the
pattern.
bazel run [target]: Compile the program represented by target and then run
it.
What is platform in Angular?
A platform is the context in which an Angular application runs. The most
common platform for Angular applications is a web browser, but it can also be an
operating system for a mobile device, or a web server. The runtime-platform is
provided by the @angular/platform-* packages and these packages allow
applications that make use of @angular/core and @angular/common to execute in
different environments. i.e, Angular can be used as platform-independent
framework in different environments, For example,
While running in the browser, it uses platform-browser package.
When SSR(server-side rendering ) is used, it uses platform-server package for
providing web server implementation.
What happens if I import the same module twice?
If multiple modules imports the same module then angular evaluates it only once
(When it encounters the module first time). It follows this condition even the
module appears at any level in a hierarchy of imported NgModules.
How do you select an element within a component
template?
You can use @ViewChild directive to access elements in the view directly. Let's
take input element with a reference,
<input #uname>
and define view child directive and access it in ngAfterViewInit lifecycle hook
@ViewChild('uname') input;
ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}
How do you detect route change in Angular?
In Angular7, you can subscribe to router to detect the changes. The subscription
for router events would be as below,
this.router.events.subscribe((event: Event) => {})
Let's take a simple component to detect router changes
import { Component } from '@angular/core';
import { Router, Event, NavigationStart, NavigationEnd,
NavigationError } from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
// Show loading indicator and perform an action
}
if (event instanceof NavigationEnd) {
// Hide loading indicator and perform an action
}
if (event instanceof NavigationError) {
// Hide loading indicator and perform an action
console.log(event.error); // It logs an error for
debugging
}
});
}
}
How do you pass headers for HTTP client?
You can directly pass object map for http client or create HttpHeaders class to
supply the headers.
constructor(private _http: HttpClient) {}
this._http.get('someUrl',{
headers: {'header1':'value1','header2':'value2'}
});
(or)
let headers = new HttpHeaders().set('header1', headerValue1); //
create header object
headers = headers.append('header2', headerValue2); // add a new
header, creating a new object
headers = headers.append('header3', headerValue3); // add another
header
let params = new HttpParams().set('param1', value1); // create
params object
params = params.append('param2', value2); // add a new param,
creating a new object
params = params.append('param3', value3); // add another param
return this._http.get<any[]>('someUrl', { headers: headers, params:
params })
What is the purpose of differential loading in CLI?
From Angular8 release onwards, the applications are built using differential
loading strategy from CLI to build two separate bundles as part of your deployed
application.
The first build contains ES2015 syntax which takes the advantage of built-in
support in modern browsers, ships less polyfills, and results in a smaller bundle
size.
The second build contains old ES5 syntax to support older browsers with all
necessary polyfills. But this results in a larger bundle size.
Note: This strategy is used to support multiple browsers but it only load the
code that the browser needs.
Does Angular supports dynamic imports?
Yes, Angular 8 supports dynamic imports in router configuration. i.e, You can use
the import statement for lazy loading the module using loadChildren method
and it will be understood by the IDEs(VSCode and WebStorm), webpack, etc.
Previously, you have been written as below to lazily load the feature module. By
mistake, if you have typo in the module name it still accepts the string and
throws an error during build time.
{path: ‘user’, loadChildren: ‘./users/user.module#UserModulee’},
This problem is resolved by using dynamic imports and IDEs are able to find it
during compile time itself.
{path: ‘user’, loadChildren: () =>
import(‘./users/user.module’).then(m => m.UserModule)};
What is lazy loading?
Lazy loading is one of the most useful concepts of Angular Routing. It helps us to
download the web pages in chunks instead of downloading everything in a big
bundle. It is used for lazy loading by asynchronously loading the feature module
for routing whenever required using the property loadChildren. Let's load
both Customer and Order feature modules lazily as below,
const routes: Routes = [
{
path: 'customers',
loadChildren: () =>
import('./customers/customers.module').then(module =>
module.CustomersModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(module
=> module.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
What are workspace APIs?
Angular 8.0 release introduces Workspace APIs to make it easier for developers
to read and modify the angular.json file instead of manually modifying it.
Currently, the only supported storage3 format is the JSON-based format used by
the Angular CLI. You can enable or add optimization option for build target as
below,
import { NodeJsSyncHost } from '@angular-devkit/core/node';
import { workspaces } from '@angular-devkit/core';
async function addBuildTargetOption() {
const host = workspaces.createWorkspaceHost(new
NodeJsSyncHost());
const workspace = await
workspaces.readWorkspace('path/to/workspace/directory/', host);
const project = workspace.projects.get('my-app');
if (!project) {
throw new Error('my-app does not exist');
}
const buildTarget = project.targets.get('build');
if (!buildTarget) {
throw new Error('build target does not exist');
}
buildTarget.options.optimization = true;
await workspaces.writeWorkspace(workspace, host);
}
addBuildTargetOption();
How do you upgrade angular version?
The Angular upgrade is quite easier using Angular CLI ng update command as
mentioned below. For example, if you upgrade from Angular 7 to 8 then your
lazy loaded route imports will be migrated to the new import syntax
automatically.
$ ng update @angular/cli @angular/core
What is Angular Material?
Angular Material is a collection of Material Design components for Angular
framework following the Material Design spec. You can apply Material Design
very easily using Angular Material. The installation can be done through npm or
yarn,
npm install --save @angular/material @angular/cdk
@angular/animations
(OR)
yarn add @angular/material @angular/cdk @angular/animations
It supports the most recent two versions of all major browsers. The latest version
of Angular material is 8.1.1
How do you upgrade location service of angularjs?
If you are using $location service in your old AngularJS application, now you can
use LocationUpgradeModule(unified location service) which puts the
responsibilities of $location service to Location service in Angular. Let's add this
module to AppModule as below,
// Other imports ...
import { LocationUpgradeModule } from '@angular/common/upgrade';
@NgModule({
imports: [
// Other NgModule imports...
LocationUpgradeModule.config()
]
})
export class AppModule {}
What is NgUpgrade?
NgUpgrade is a library put together by the Angular team, which you can use in
your applications to mix and match AngularJS and Angular components and
bridge the AngularJS and Angular dependency injection systems.
How do you test Angular application using CLI?
Angular CLI downloads and install everything needed with the Jasmine Test
framework. You just need to run ng test to see the test results. By default this
command builds the app in watch mode, and launches the Karma test runner.
The output of test results would be as below,
10% building modules 1/1 modules 0 active
...INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
...INFO [launcher]: Launching browser Chrome ...
...INFO [launcher]: Starting browser Chrome
...INFO [Chrome ...]: Connected on socket ...
Chrome ...: Executed 3 of 3 SUCCESS (0.135 secs / 0.205 secs)
Note: A chrome browser also opens and displays the test output in the "Jasmine
HTML Reporter".
How to use polyfills in Angular application?
The Angular CLI provides support for polyfills officially. When you create a new
project with the ng new command, a src/polyfills.ts configuration file is
created as part of your project folder. This file includes the mandatory and many
of the optional polyfills as JavaScript import statements. Let's categorize the
polyfills,
Mandatory polyfills: These are installed automatically when you create your
project with ng new command and the respective import statements enabled in
'src/polyfills.ts' file.
Optional polyfills: You need to install its npm package and then create import
statement in 'src/polyfills.ts' file. For example, first you need to install below npm
package for adding web animations (optional) polyfill. bash npm install --save
web-animations-js and create import statement in polyfill file. javascript import
'web-animations-js';
What are the ways to trigger change detection in Angular?
You can inject either ApplicationRef or NgZone, or ChangeDetectorRef into your
component and apply below specific methods to trigger change detection in
Angular. i.e, There are 3 possible ways,
ApplicationRef.tick(): Invoke this method to explicitly process change
detection and its side-effects. It check the full component tree.
NgZone.run(callback): It evaluate the callback function inside the Angular
zone.
ChangeDetectorRef.detectChanges(): It detects only the components and
it's children.
What are the differences of various versions of Angular?
There are different versions of Angular framework. Let's see the features of all
the various versions,
Angular 1:
Angular 1 (AngularJS) is the first angular framework released in the year 2010.
AngularJS is not built for mobile devices.
It is based on controllers with MVC architecture.
Angular 2:
Angular 2 was released in the year 2016. Angular 2 is a complete rewrite of
Angular1 version.
The performance issues that Angular 1 version had has been addressed in
Angular 2 version.
Angular 2 is built from scratch for mobile devices unlike Angular 1 version.
Angular 2 is components based.
Angular 3:
The following are the different package versions in Angular 2:
@angular/core v2.3.0
@angular/compiler v2.3.0
@angular/http v2.3.0
@angular/router v3.3.0
The router package is already versioned 3 so to avoid confusion switched to
Angular 4 version and skipped 3 version.
Angular 4:
The compiler generated code file size in AOT mode is very much reduced.
With Angular 4 the production bundles size is reduced by hundreds of KB’s.
Animation features are removed from angular/core and formed as a separate
package.
Supports Typescript 2.1 and 2.2.
Angular Universal
New HttpClient
Angular 5:
Angular 5 makes angular faster. It improved the loading time and execution
time.
Shipped with new build optimizer.
Supports Typescript 2.5.
Service Worker
Angular 6:
It is released in May 2018.
Includes Angular Command Line Interface (CLI), Component Development KIT
(CDK), Angular Material Package, Angular Elements.
Service Worker bug fixes.
i18n
Experimental mode for Ivy.
RxJS 6.0
Tree Shaking
Angular 7:
It is released in October 2018.
TypeScript 3.1
RxJS 6.3
New Angular CLI
CLI Prompts capability provide an ability to ask questions to the user before they
run. It is like interactive dialog between the user and the CLI
With the improved CLI Prompts capability, it helps developers to make the
decision. New ng commands ask users for routing and CSS styles types(SCSS)
and ng add @angular/material asks for themes and gestures or animations.
Angular 8:
It is released in May 2019.
TypeScript 3.4
Angular 9:
It is released in February 2020.
TypeScript 3.7
Ivy enabled by default
Angular 10:
It is released in June 2020.
TypeScript 3.9
TSlib 2.0
What are the security principles in angular?
Below are the list of security principles in angular,
You should avoid direct use of the DOM APIs.
You should enable Content Security Policy (CSP) and configure your web server
to return appropriate CSP HTTP headers.
You should Use the offline template compiler.
You should Use Server Side XSS protection.
You should Use DOM Sanitizer.
You should Preventing CSRF or XSRF attacks.
What is the reason to deprecate Web Tracing Framework?
Angular has supported the integration with the Web Tracing Framework (WTF)
for the purpose of performance testing. Since it is not well maintained and failed
in majority of the applications, the support is deprecated in latest releases.
What is the reason to deprecate web worker packages?
Both @angular/platform-webworker and @angular/platform-webworker-dynamic ar
e officially deprecated, the Angular team realized it's not good practice to run the
Angular application on Web worker
How do you find angular CLI version?
Angular CLI provides it's installed version using below different ways using ng
command,
ng v
ng version
ng -v
ng --version
and the output would be as below,
Angular CLI: 1.6.3
Node: 8.11.3
OS: darwin x64
Angular:
...
What is the browser support for Angular?
Angular supports most recent browsers which includes both desktop and mobile
browsers.
Browser Version
Chrome latest
Firefox latest
Edge 2 most recent major versions
IE 11, 10, 9 (Compatibility mode is not supported)
Safari 2 most recent major versions
IE Mobile 11
iOS 2 most recent major versions
Android 7.0, 6.0, 5.0, 5.1, 4.4
What is schematic?
It's a scaffolding library that defines how to generate or transform a
programming project by creating, modifying, refactoring, or moving files and
code. It defines rules that operate on a virtual file system called a tree.
What is rule in Schematics?
In schematics world, it's a function that operates on a file tree to create, delete,
or modify files in a specific manner.
What is Schematics CLI?
Schematics come with their own command-line tool known as Schematics CLI. It
is used to install the schematics executable, which you can use to create a new
schematics collection with an initial named schematic. The collection folder is a
workspace for schematics. You can also use the schematics command to add a
new schematic to an existing collection, or extend an existing schematic. You
can install Schematic CLI globally as below,
npm install -g @angular-devkit/schematics-cli
What are the best practices for security in angular?
Below are the best practices of security in angular,
Use the latest Angular library releases
Don't modify your copy of Angular
Avoid Angular APIs marked in the documentation as “Security Risk.”
What is Angular security model for preventing XSS attacks?
Angular treats all values as untrusted by default. i.e, Angular sanitizes and
escapes untrusted values When a value is inserted into the DOM from a
template, via property, attribute, style, class binding, or interpolation.
What is the role of template compiler for prevention of XSS
attacks?
The offline template compiler prevents vulnerabilities caused by template
injection, and greatly improves application performance. So it is recommended
to use offline template compiler in production deployments without dynamically
generating any template.
What are the various security contexts in Angular?
Angular defines the following security contexts for sanitization,
HTML: It is used when interpreting a value as HTML such as binding to
innerHtml.
Style: It is used when binding CSS into the style property.
URL: It is used for URL properties such as <a href>.
Resource URL: It is a URL that will be loaded and executed as code such
as <script src>.
What is Sanitization? Does angular supports it?
Sanitization is the inspection of an untrusted value, turning it into a value that's
safe to insert into the DOM. Yes, Angular supports sanitization. It sanitizes
untrusted values for HTML, styles, and URLs but sanitizing resource URLs isn't
possible because they contain arbitrary code.
What is the purpose of innerHTML?
The innerHtml is a property of HTML-Elements, which allows you to set it's html-
content programmatically. Let's display the below html code snippet in
a <div> tag as below using innerHTML binding,
<div [innerHTML]="htmlSnippet"></div>
and define the htmlSnippet property from any component
export class myComponent {
htmlSnippet: string = '<b>Hello World</b>, Angular';
}
Unfortunately this property could cause Cross Site Scripting (XSS) security bugs
when improperly handled.
What is the difference between interpolated content and
innerHTML?
The main difference between interpolated and innerHTML code is the behavior of
code interpreted. Interpolated content is always escaped i.e, HTML isn't
interpreted and the browser displays angle brackets in the element's text
content. Where as in innerHTML binding, the content is interpreted i.e, the
browser will convert < and > characters as HTMLEntities. For example, the
usage in template would be as below,
<p>Interpolated value:</p>
<div >{{htmlSnippet}}</div>
<p>Binding of innerHTML:</p>
<div [innerHTML]="htmlSnippet"></div>
and the property defined in a component.
export class InnerHtmlBindingComponent {
htmlSnippet = 'Template <script>alert("XSS Attack")</script>
<b>Code attached</b>';
}
Even though innerHTML binding create a chance of XSS attack, Angular
recognizes the value as unsafe and automatically sanitizes it.
How do you prevent automatic sanitization?
Sometimes the applications genuinely need to include executable code such as
displaying <iframe> from an URL. In this case, you need to prevent automatic
sanitization in Angular by saying that you inspected a value, checked how it was
generated, and made sure it will always be secure. Basically it involves 2 steps,
Inject DomSanitizer: You can inject DomSanitizer in component as parameter in
constructor
Mark the trusted value by calling some of the below methods
bypassSecurityTrustHtml
bypassSecurityTrustScript
bypassSecurityTrustStyle
bypassSecurityTrustUrl
bypassSecurityTrustResourceUrl
For example,The usage of dangerous url to trusted url would be as below,
constructor(private sanitizer: DomSanitizer) {
this.dangerousUrl = 'javascript:alert("XSS attack")';
this.trustedUrl =
sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);
Is safe to use direct DOM API methods in terms of security?
No,the built-in browser DOM APIs or methods don't automatically protect you
from security vulnerabilities. In this case it is recommended to use Angular
templates instead of directly interacting with DOM. If it is unavoidable then use
the built-in Angular sanitization functions.
What is DOM sanitizer?
DomSanitizer is used to help preventing Cross Site Scripting Security bugs (XSS)
by sanitizing values to be safe to use in the different DOM contexts.
How do you support server side XSS protection in Angular
application?
The server-side XSS protection is supported in an angular application by using a
templating language that automatically escapes values to prevent XSS
vulnerabilities on the server. But don't use a templating language to generate
Angular templates on the server side which creates a high risk of introducing
template-injection vulnerabilities.
Is angular prevents http level vulnerabilities?
Angular has built-in support for preventing http level vulnerabilities such as
cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI).
Even though these vulnerabilities need to be mitigated on server-side, Angular
provides helpers to make the integration easier on the client side.
HttpClient supports a token mechanism used to prevent XSRF attacks
HttpClient library recognizes the convention of prefixed JSON responses(which
non-executable js code with ")]}',\n" characters) and automatically strips the
string ")]}',\n" from all responses before further parsing
What are Http Interceptors?
Http Interceptors are part of @angular/common/http, which inspect and
transform HTTP requests from your application to the server and vice-versa on
HTTP responses. These interceptors can perform a variety of implicit tasks, from
authentication to logging.
The syntax of HttpInterceptor interface looks like as below,
interface HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>>
}
You can use interceptors by declaring a service class that implements the
intercept() method of the HttpInterceptor interface.
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
...
}
}
After that you can use it in your module,
@NgModule({
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true
}
]
...
})
export class AppModule {}
What are the applications of HTTP interceptors?
The HTTP Interceptors can be used for different variety of tasks,
Authentication
Logging
Caching
Fake backend
URL transformation
Modifying headers
Is multiple interceptors supported in Angular?
Yes, Angular supports multiple interceptors at a time. You could define multiple
interceptors in providers property:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyFirstInterceptor, multi:
true },
{ provide: HTTP_INTERCEPTORS, useClass: MySecondInterceptor,
multi: true }
],
The interceptors will be called in the order in which they were provided. i.e,
MyFirstInterceptor will be called first in the above interceptors configuration.
How can I use interceptor for an entire application?
You can use same instance of HttpInterceptors for the entire app by importing
the HttpClientModule only in your AppModule, and add the interceptors to the
root application injector. For example, let's define a class that is injectable in root
application.
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).do(event => {
if (eventt instanceof HttpResponse) {
// Code goes here
}
});
}
}
After that import HttpClientModule in AppModule
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi:
true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
How does Angular simplifies Internationalization?
Angular simplifies the below areas of internationalization,
Displaying dates, number, percentages, and currencies in a local format.
Preparing text in component templates for translation.
Handling plural forms of words.
Handling alternative text.
How do you manually register locale data?
By default, Angular only contains locale data for en-US which is English as
spoken in the United States of America . But if you want to set to another locale,
you must import locale data for that new locale. After that you can register
using registerLocaleData method and the syntax of this method looks like
below,
registerLocaleData(data: any, localeId?: any, extraData?: any): void
For example, let us import German locale and register it in the application
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
registerLocaleData(localeDe, 'de');
What are the four phases of template translation?
The i18n template translation process has four phases:
Mark static text messages in your component templates for
translation: You can place i18n on every element tag whose fixed text is to be
translated. For example, you need i18n attribue for heading as below,
<h1 i18n>Hello i18n!</h1>
Create a translation file: Use the Angular CLI xi18n command to extract the
marked text into an industry-standard translation source file. i.e, Open terminal
window at the root of the app project and run the CLI command xi18n.
ng xi18n
The above command creates a file named messages.xlf in your project's root
directory.
Note: You can supply command options to change the format, the name, the
location, and the source locale of the extracted file.
Edit the generated translation file: Translate the extracted text into the
target language. In this step, create a localization folder (such as locale)under
root directory(src) and then create target language translation file by copying
and renaming the default messages.xlf file. You need to copy source text node
and provide the translation under target tag. For example, create the translation
file(messages.de.xlf) for German language
<trans-unit id="greetingHeader" datatype="html">
<source>Hello i18n!</source>
<target>Hallo i18n !</target>
<note priority="1" from="description">A welcome header for this
sample</note>
<note priority="1" from="meaning">welcome message</note>
</trans-unit>
Merge the completed translation file into the app: You need to use Angular
CLI build command to compile the app, choosing a locale-specific configuration,
or specifying the following command options.
--i18nFile=path to the translation file
--i18nFormat=format of the translation file
--i18nLocale= locale id
What is the purpose of i18n attribute?
The Angular i18n attribute marks translatable content. It is a custom attribute,
recognized by Angular tools and compilers. The compiler removes it after
translation.
Note: Remember that i18n is not an Angular directive.
What is the purpose of custom id?
When you change the translatable text, the Angular extractor tool generates a
new id for that translation unit. Because of this behavior, you must then update
the translation file with the new id every time.
For example, the translation file messages.de.xlf.html has generated trans-unit
for some text message as below
<trans-unit id="827wwe104d3d69bf669f823jjde888" datatype="html">
You can avoid this manual update of id attribute by specifying a custom id in the
i18n attribute by using the prefix @@.
<h1 i18n="@@welcomeHeader">Hello i18n!</h1>
What happens if the custom id is not unique?
You need to define custom ids as unique. If you use the same id for two different
text messages then only the first one is extracted. But its translation is used in
place of both original text messages.
For example, let's define same custom id myCustomId for two messages,
<h2 i18n="@@myCustomId">Good morning</h3>
<!-- ... -->
<h2 i18n="@@myCustomId">Good night</p>
and the translation unit generated for first text in for German language as
<trans-unit id="myId" datatype="html">
<source>Good morning</source>
<target state="new">Guten Morgen</target>
</trans-unit>
Since custom id is the same, both of the elements in the translation contain the
same text as below
<h2>Guten Morgen</h2>
<h2>Guten Morgen</h2>
Can I translate text without creating an element?
Yes, you can achieve using <ng-container> attribute. Normally you need to wrap
a text content with i18n attribute for the translation. But if you don't want to
create a new DOM element just for the sake of translation, you can wrap the text
in an element.
<ng-container i18n>I'm not using any DOM element for
translation</ng-container>
Remember that <ng-container> is transformed into an html comment
How can I translate attribute?
You can translate attributes by attaching i18n-x attribute where x is the name of
the attribute to translate. For example, you can translate image title attribute as
below,
<img [src]="example" i18n-title title="Internationlization" />
By the way, you can also assign meaning, description and id with the i18n-x="|
@@" syntax.
List down the pluralization categories?
Pluralization has below categories depending on the language.
=0 (or any other number)
zero
one
two
few
many
other
What is select ICU expression?
ICU expression is similar to the plural expressions except that you choose among
alternative translations based on a string value instead of a number. Here you
define those string values.
Let's take component binding with residenceStatus property which has "citizen",
"permanent resident" and "foreigner" possible values and the message maps
those values to the appropriate translations.
<span i18n>The person is {residenceStatus, select, citizen {citizen}
permanent resident {permanentResident} foreigner {foreigner}}</span>
How do you report missing translations?
By default, When translation is missing, it generates a warning message such as
"Missing translation for message 'somekey'". But you can configure with a
different level of message in Angular compiler as below,
Error: It throws an error. If you are using AOT compilation, the build will fail. But
if you are using JIT compilation, the app will fail to load.
Warning (default): It shows a 'Missing translation' warning in the console or
shell.
Ignore: It doesn't do anything.
If you use AOT compiler then you need to perform changes
in configurations section of your Angular CLI configuration file, angular.json.
"configurations": {
...
"de": {
...
"i18nMissingTranslation": "error"
}
}
If you use the JIT compiler, specify the warning level in the compiler config at
bootstrap by adding the 'MissingTranslationStrategy' property as below,
import { MissingTranslationStrategy } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-
dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule, {
missingTranslation: MissingTranslationStrategy.Error,
providers: [
// ...
]
});
How do you provide build configuration for multiple
locales?
You can provide build configuration such as translation file path, name, format
and application url in configuration settings of Angular.json file. For example,
the German version of your application configured the build as follows,
"configurations": {
"de": {
"aot": true,
"outputPath": "dist/my-project-de/",
"baseHref": "/fr/",
"i18nFile": "src/locale/messages.de.xlf",
"i18nFormat": "xlf",
"i18nLocale": "de",
"i18nMissingTranslation": "error",
}
What is an angular library?
An Angular library is an Angular project that differs from an app in that it cannot
run on its own. It must be imported and used in an app. For example, you can
import or add service worker library to an Angular application which turns an
application into a Progressive Web App (PWA).
Note: You can create own third party library and publish it as npm package to be
used in an Application.
What is AOT compiler?
The AOT compiler is part of a build process that produces a small, fast, ready-to-
run application package, typically for production. It converts your Angular HTML
and TypeScript code into efficient JavaScript code during the build phase before
the browser downloads and runs that code.
How do you select an element in component template?
You can control any DOM element via ElementRef by injecting it into your
component's constructor. i.e, The component should have constructor with
ElementRef parameter,
constructor(myElement: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
What is TestBed?
TestBed is an api for writing unit tests for Angular applications and it's libraries.
Even though We still write our tests in Jasmine and run using Karma, this API
provides an easier way to create components, handle injection, test
asynchronous behaviour and interact with our application.
What is protractor?
Protractor is an end-to-end test framework for Angular and AngularJS
applications. It runs tests against your application running in a real browser,
interacting with it as a user would.
npm install -g protractor
What is collection?
Collection is a set of related schematics collected in an npm package. For
example, @schematics/angular collection is used in Angular CLI to apply
transforms to a web-app project. You can create your own schematic collection
for customizing angular projects.
How do you create schematics for libraries?
You can create your own schematic collections to integrate your library with the
Angular CLI. These collections are classified as 3 main schematics,
Add schematics: These schematics are used to install library in an Angular
workspace using ng add command. For example, @angular/material schematic
tells the add command to install and set up Angular Material and theming.
Generate schematics: These schematics are used to modify projects, add
configurations and scripts, and scaffold artifacts in library using ng
generate command. For example, @angular/material generation schematic
supplies generation schematics for the UI components. Let's say the table
component is generated using ng generate @angular/material:table .
Update schematics: These schematics are used to update library's
dependencies and adjust for breaking changes in a new library release using ng
update command. For example, @angular/material update schematic updates
material and cdk dependencies using ng update @angular/material command.
How do you use jquery in Angular?
You can use jquery in Angular using 3 simple steps,
Install the dependency: At first, install the jquery dependency using npm
npm install --save jquery
Add the jquery script: In Angular-CLI project, add the relative path to jquery in
the angular.json file.
"scripts": [
"node_modules/jquery/dist/jquery.min.js"
]
Start using jquery: Define the element in template. Whereas declare the
jquery variable and apply CSS classes on the element.
<div id="elementId">
<h1>JQuery integration</h1>
</div>
import {Component, OnInit} from '@angular/core';
declare var $: any; // (or) import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit(): void {
$(document).ready(() => {
$('#elementId').css({'text-color': 'blue', 'font-size':
'150%'});
});
}
}
What is the reason for No provider for HTTP exception?
This exception is due to missing HttpClientModule in your module. You just need
to import in module as below,
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
What is router state?
The RouteState is an interface which represents the state of the router as a tree
of activated routes.
interface RouterState extends Tree {
snapshot: RouterStateSnapshot
toString(): string
}
You can access the current RouterState from anywhere in the Angular app using
the Router service and the routerState property.
How can I use SASS in angular project?
When you are creating your project with angular cli, you can use ng
newcommand. It generates all your components with predefined sass files.
ng new My_New_Project --style=sass
But if you are changing your existing style in your project then use ng
set command,
ng set defaults.styleExt scss
What is the purpose of hidden property?
The hidden property is used to show or hide the associated DOM element, based
on an expression. It can be compared close to ng-show directive in AngularJS.
Let's say you want to show user name based on the availability of user
using hidden property.
<div [hidden]="!user.name">
My name is: {{user.name}}
</div>
What is the difference between ngIf and hidden property?
The main difference is that *ngIf will remove the element from the DOM, while
[hidden] actually plays with the CSS style by setting display:none. Generally it is
expensive to add and remove stuff from the DOM for frequent actions.
What is slice pipe?
The slice pipe is used to create a new Array or String containing a subset (slice)
of the elements. The syntax looks like as below,
{{ value_expression | slice : start [ : end ] }}
For example, you can provide 'hello' list based on a greeting array,
@Component({
selector: 'list-pipe',
template: `<ul>
<li *ngFor="let i of greeting | slice:0:5">{{i}}</li>
</ul>`
})
export class PipeListComponent {
greeting: string[] = ['h', 'e', 'l', 'l', 'o', 'm','o', 'r', 'n',
'i', 'n', 'g'];
}
What is index property in ngFor directive?
The index property of the NgFor directive is used to return the zero-based index
of the item in each iteration. You can capture the index in a template input
variable and use it in the template.
For example, you can capture the index in a variable named indexVar and
displays it with the todo's name using ngFor directive as below.
<div *ngFor="let todo of todos; let i=index">{{i + 1}} -
{{todo.name}}</div>
What is the purpose of ngFor trackBy?
The main purpose of using *ngFor with trackBy option is performance
optimization. Normally if you use NgFor with large data sets, a small change to
one item by removing or adding an item, can trigger a cascade of DOM
manipulations. In this case, Angular sees only a fresh list of new object
references and to replace the old DOM elements with all new DOM elements. You
can help Angular to track which items added or removed by providing
a trackBy function which takes the index and the current item as arguments and
needs to return the unique identifier for this item.
For example, lets set trackBy to the trackByTodos() method
<div *ngFor="let todo of todos; trackBy: trackByTodos">
({{todo.id}}) {{todo.name}}
</div>
and define the trackByTodos method,
trackByTodos(index: number, item: Todo): number { return todo.id; }
What is the purpose of ngSwitch directive?
NgSwitch directive is similar to JavaScript switch statement which displays one
element from among several possible elements, based on a switch condition. In
this case only the selected element placed into the DOM. It has been used along
with NgSwitch, NgSwitchCase and NgSwitchDefault directives.
For example, let's display the browser details based on selected browser using
ngSwitch directive.
<div [ngSwitch]="currentBrowser.name">
<chrome-browser *ngSwitchCase="'chrome'"
[item]="currentBrowser"></chrome-browser>
<firefox-browser *ngSwitchCase="'firefox'"
[item]="currentBrowser"></firefox-browser>
<opera-browser *ngSwitchCase="'opera'"
[item]="currentBrowser"></opera-browser>
<safari-browser *ngSwitchCase="'safari'"
[item]="currentBrowser"></safari-browser>
<ie-browser *ngSwitchDefault [item]="currentItem"></ie-
browser>
</div>
Is it possible to do aliasing for inputs and outputs?
Yes, it is possible to do aliasing for inputs and outputs in two ways.
Aliasing in metadata: The inputs and outputs in the metadata aliased using a
colon-delimited (:) string with the directive property name on the left and the
public alias on the right. i.e. It will be in the format of propertyName:alias.
inputs: ['input1: buyItem'],
outputs: ['outputEvent1: completedEvent']
Aliasing with @Input()/@Output() decorator: The alias can be specified for
the property name by passing the alias name to the @Input()/@Output()
decorator.i.e. It will be in the form of @Input(alias) or @Output(alias).
@Input('buyItem') input1: string;
@Output('completedEvent') outputEvent1 = new EventEmitter<string>();
What is safe navigation operator?
The safe navigation operator(?)(or known as Elvis Operator) is used to guard
against null and undefined values in property paths when you are not aware
whether a path exists or not. i.e. It returns value of the object path if it exists,
else it returns the null value.
For example, you can access nested properties of a user profile easily without
null reference errors as below,
<p>The user firstName is: {{user?.fullName.firstName}}</p>
Using this safe navigation operator, Angular framework stops evaluating the
expression when it hits the first null value and renders the view without any
errors.
Is any special configuration required for Angular9?
You don't need any special configuration. In Angular9, the Ivy renderer is the
default Angular compiler. Even though Ivy is available Angular8 itself, you had to
configure it in tsconfig.json file as below,
"angularCompilerOptions": { "enableIvy": true }
What are type safe TestBed API changes in Angular9?
Angular 9 provides type safe changes in TestBed API changes by replacing the
old get function with the new inject method. Because TestBed.get method is not
type-safe. The usage would be as below,
TestBed.get(ChangeDetectorRef) // returns any. It is deprecated now.
TestBed.inject(ChangeDetectorRef) // returns ChangeDetectorRef
Is mandatory to pass static flag for ViewChild?
In Angular 8, the static flag is required for ViewChild. Whereas in Angular9, you
no longer need to pass this property. Once you updated to Angular9 using ng
update, the migration will remove { static: false } script everywhere.
@ViewChild(ChildDirective) child: ChildDirective; // Angular9 usage
@ViewChild(ChildDirective, { static: false }) child: ChildDirective;
//Angular8 usage
What are the list of template expression operators?
The Angular template expression language supports three special template
expression operators.
Pipe operator
Safe navigation operator
Non-null assertion operator
What is the precedence between pipe and ternary
operators?
The pipe operator has a higher precedence than the ternary operator (?:). For
example, the expression first ? second : third | fourth is parsed as first ?
second : (third | fourth).
What is an entry component?
An entry component is any component that Angular loads imperatively(i.e, not
referencing it in the template) by type. Due to this behavior, they can’t be found
by the Angular compiler during compilation. These components created
dynamically with ComponentFactoryResolver.
Basically, there are two main kinds of entry components which are following -
The bootstrapped root component
A component you specify in a route
What is a bootstrapped component?
A bootstrapped component is an entry component that Angular loads into the
DOM during the bootstrap process or application launch time. Generally, this
bootstrapped or root component is named as AppComponent in your root module
using bootstrap property as below.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent] // bootstrapped entry component need to
be declared here
})
How do you manually bootstrap an application?
You can use ngDoBootstrap hook for a manual bootstrapping of the application
instead of using bootstrap array in @NgModule annotation. This hook is part
of DoBootstap interface.
interface DoBootstrap {
ngDoBootstrap(appRef: ApplicationRef): void
}
The module needs to be implement the above interface to use the hook for
bootstrapping.
class AppModule implements DoBootstrap {
ngDoBootstrap(appRef: ApplicationRef) {
appRef.bootstrap(AppComponent); // bootstrapped entry component
need to be passed
}
}
Is it necessary for bootstrapped component to be entry
component?
Yes, the bootstrapped component needs to be an entry component. This is
because the bootstrapping process is an imperative process.
What is a routed entry component?
The components referenced in router configuration are called as routed entry
components. This routed entry component defined in a route definition as below,
const routes: Routes = [
{
path: '',
component: TodoListComponent // router entry component
}
];
Since router definition requires you to add the component in two places (router
and entryComponents), these components are always entry components.
Note: The compilers are smart enough to recognize a router definition and
automatically add the router component into entryComponents.
Why is not necessary to use entryComponents array every
time?
Most of the time, you don't need to explicity to set entry components in
entryComponents array of ngModule decorator. Because angular adds
components from both @NgModule.bootstrap and route definitions to entry
components automatically.
Do I still need to use entryComponents array in Angular9?
No. In previous angular releases, the entryComponents array of ngModule
decorator is used to tell the compiler which components would be created and
inserted dynamically in the view. In Angular9, this is not required anymore with
Ivy.
Is it all components generated in production build?
No, only the entry components and template components appears in production
builds. If a component isn't an entry component and isn't found in a template,
the tree shaker will throw it away. Due to this reason, make sure to add only true
entry components to reduce the bundle size.
What is Angular compiler?
The Angular compiler is used to convert the application code into JavaScript
code. It reads the template markup, combines it with the corresponding
component class code, and emits component factories which creates JavaScript
representation of the component along with elements of @Component metadata.
What is the role of ngModule metadata in compilation
process?
The @NgModule metadata is used to tell the Angular compiler what components to
be compiled for this module and how to link this module with other modules.
How does angular finds components, directives and pipes?
The Angular compiler finds a component or directive in a template when it can
match the selector of that component or directive in that template. Whereas it
finds a pipe if the pipe's name appears within the pipe syntax of the template
HTML.
Give few examples for NgModules?
The Angular core libraries and third-party libraries are available as NgModules.
Angular libraries such as FormsModule, HttpClientModule, and RouterModule are
NgModules.
Many third-party libraries such as Material Design, Ionic, and AngularFire2 are
NgModules.
What are feature modules?
Feature modules are NgModules, which are used for the purpose of organizing
code. The feature module can be created with Angular CLI using the below
command in the root directory,
ng generate module MyCustomFeature //
Angular CLI creates a folder called my-custom-feature with a file inside called my-
custom-feature.module.ts with the following contents
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
imports: [
CommonModule
],
declarations: []
})
export class MyCustomFeature { }
Note: The "Module" suffix shouldn't present in the name because the CLI
appends it.
What are the imported modules in CLI generated feature
modules?
In the CLI generated feature module, there are two JavaScript import statements
at the top of the file
NgModule: InOrder to use the @NgModule decorator
CommonModule: It provides many common directives such as ngIf and ngFor.
What are the differences between ngmodule and javascript
module?
Below are the main differences between Angular NgModule and javascript
module,
NgModule JavaScript module
NgModule bounds declarable classes only There is no restriction classes
Can define all member classes
List the module's classes in declarations array only
in one giant file
It only export the declarable classes it owns or
It can export any classes
imports from other modules
Extend the entire application with services by Can't extend the application
adding providers to provides array with services
What are the possible errors with declarations?
There are two common possible errors with declarations array,
If you use a component without declaring it, Angular returns an error message.
If you try to declare the same class in more than one module then compiler
emits an error.
What are the steps to use declaration elements?
Below are the steps to be followed to use declaration elements.
Create the element(component, directive and pipes) and export it from the file
where you wrote it
Import it into the appropriate module.
Declare it in the @NgModule declarations array.
What happens if browserModule used in feature module?
If you do import BrowserModule into a lazy loaded feature module, Angular
returns an error telling you to use CommonModule instead. Because
BrowserModule’s providers are for the entire app so it should only be in the root
module, not in feature module. Whereas Feature modules only need the common
directives in CommonModule.
What are the types of feature modules?
Below are the five categories of feature modules,
Domain: Deliver a user experience dedicated to a particular application
domain(For example, place an order, registration etc)
Routed: These are domain feature modules whose top components are the
targets of router navigation routes.
Routing: It provides routing configuration for another module.
Service: It provides utility services such as data access and messaging(For
example, HttpClientModule)
Widget: It makes components, directives, and pipes available to external
modules(For example, third-party libraries such as Material UI)
What is a provider?
A provider is an instruction to the Dependency Injection system on how to obtain
a value for a dependency(aka services created). The service can be provided
using Angular CLI as below,
ng generate service my-service
The created service by CLI would be as below,
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root', //Angular provide the service in root injector
})
export class MyService {
}
What is the recommendation for provider scope?
You should always provide your service in the root injector unless there is a case
where you want the service to be available only if you import a particular
@NgModule.
How do you restrict provider scope to a module?
It is possible to restrict service provider scope to a specific module instead
making available to entire application. There are two possible ways to do it.
Using providedIn in service:
import { Injectable } from '@angular/core';
import { SomeModule } from './some.module';
@Injectable({
providedIn: SomeModule,
})
export class SomeService {
}
Declare provider for the service in module:
import { NgModule } from '@angular/core';
import { SomeService } from './some.service';
@NgModule({
providers: [SomeService],
})
export class SomeModule {
}
How do you provide a singleton service?
There are two possible ways to provide a singleton service.
Set the providedIn property of the @Injectable() to "root". This is the preferred
way(starting from Angular 6.0) of creating a singleton service since it makes
your services tree-shakable.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MyService {
}
Include the service in root module or in a module that is only imported by root
module. It has been used to register services before Angular 6.0.
@NgModule({
...
providers: [MyService],
...
})
What are the different ways to remove duplicate service
registration?
If a module defines provides and declarations then loading the module in
multiple feature modules will duplicate the registration of the service. Below are
the different ways to prevent this duplicate behavior.
Use the providedIn syntax instead of registering the service in the module.
Separate your services into their own module.
Define forRoot() and forChild() methods in the module.
How does forRoot method helpful to avoid duplicate router
instances?
If the RouterModule module didn’t have forRoot() static method then each feature
module would instantiate a new Router instance, which leads to broken
application due to duplicate instances. After using forRoot() method, the root
application module imports RouterModule.forRoot(...) and gets a Router, and all
feature modules import RouterModule.forChild(...) which does not instantiate
another Router.
What is a shared module?
The Shared Module is the module in which you put commonly used directives,
pipes, and components into one module that is shared(import it) throughout the
application.
For example, the below shared module imports CommonModule, FormsModule
for common directives and components, pipes and directives based on the need,
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UserComponent } from './user.component';
import { NewUserDirective } from './new-user.directive';
import { OrdersPipe } from './orders.pipe';
@NgModule({
imports: [ CommonModule ],
declarations: [ UserComponent, NewUserDirective, OrdersPipe ],
exports: [ UserComponent, NewUserDirective, OrdersPipe,
CommonModule, FormsModule ]
})
export class SharedModule { }
Can I share services using modules?
No, it is not recommended to share services by importing module. i.e Import
modules when you want to use directives, pipes, and components only. The best
approach to get a hold of shared services is through 'Angular dependency
injection' because importing a module will result in a new service instance.
How do you get current direction for locales?
In Angular 9.1, the API method getLocaleDirection can be used to get the
current direction in your app. This method is useful to support Right to Left
locales for your Internationalization based applications.
import { getLocaleDirection, registerLocaleData } from
'@angular/common';
import { LOCALE_ID } from '@angular/core';
import localeAr from '@angular/common/locales/ar';
...
constructor(@Inject(LOCALE_ID) locale) {
const directionForLocale = getLocaleDirection(locale); //
Returns 'rtl' or 'ltr' based on the current locale
registerLocaleData(localeAr, 'ar-ae');
const direction = getLocaleDirection('ar-ae'); // Returns 'rtl'
// Current direction is used to provide conditional logic here
}
What is ngcc?
The ngcc(Angular Compatibility Compiler) is a tool which upgrades node_module
compiled with non-ivy ngc into ivy compliant format. The postinstall script from
package.json will make sure your node_modules will be compatible with the Ivy
renderer.
"scripts": {
"postinstall": "ngcc"
}
Whereas, Ivy compiler (ngtsc), which compiles Ivy-compatible code.
What classes should not be added to declarations?
The below class types shouldn't be added to declarations
A class which is already declared in any another module.
Directives imported from another module.
Module classes.
Service classes.
Non-Angular classes and objects, such as strings, numbers, functions, entity
models, configurations, business logic, and helper classes.
What is NgZone?
Angular provides a service called NgZone which creates a zone
named angular to automatically trigger change detection when the following
conditions are satisfied.
When a sync or async function is executed.
When there is no microTask scheduled.
What is NoopZone?
Zone is loaded/required by default in Angular applications and it helps Angular to
know when to trigger the change detection. This way, it make sures developers
focus on application development rather core part of Angular. You can also use
Angular without Zone but the change detection need to be implemented on your
own and noop zone need `to be configured in bootstrap process. Let's follow the
below two steps to remove zone.js,
Remove the zone.js import from polyfills.ts.
/
********************************************************************
*******************************
* Zone JS is required by default for Angular itself.
*/
// import 'zone.js/dist/zone'; // Included with Angular CLI.
Bootstrap Angular with noop zone in src/main.ts.
platformBrowserDynamic().bootstrapModule(AppModule, {ngZone:
'noop'})
.catch(err => console.error(err));
How do you create displayBlock components?
By default, Angular CLI creates components in an inline displayed mode(i.e,
display:inline). But it is possible to create components with display: block style
using displayBlock option,
ng generate component my-component --displayBlock
(OR) the option can be turned on by default in Angular.json
with schematics.@schematics/angular:component.displayBlock key value as true.
What are the possible data update scenarios for change
detection?
The change detection works in the following scenarios where the data changes
needs to update the application HTML.
Component initialization: While bootstrapping the Angular application,
Angular triggers the ApplicationRef.tick() to call change detection and View
Rendering.
Event listener: The DOM event listener can update the data in an Angular
component and trigger the change detection too.
@Component({
selector: 'app-event-listener',
template: `
<button (click)="onClick()">Click</button>
{{message}}`
})
export class EventListenerComponent {
message = '';
onClick() {
this.message = 'data updated';
}
}
HTTP Data Request: You can get data from a server through an HTTP request
data = 'default value';
constructor(private httpClient: HttpClient) {}
ngOnInit() {
this.httpClient.get(this.serverUrl).subscribe(response => {
this.data = response.data; // change detection will happen
automatically
});
}
Macro tasks setTimeout() or setInterval(): You can update the data in the
callback function of setTimeout or setInterval
data = 'default value';
ngOnInit() {
setTimeout(() => {
this.data = 'data updated'; // Change detection will happen
automatically
});
}
Micro tasks Promises: You can update the data in the callback function of
promise
data = 'initial value';
ngOnInit() {
Promise.resolve(1).then(v => {
this.data = v; // Change detection will happen automatically
});
}
Async operations like Web sockets and Canvas: The data can be updated
asynchronously using WebSocket.onmessage() and Canvas.toBlob().
What is a zone context?
Execution Context is an abstract concept that holds information about the
environment within the current code being executed. A zone provides an
execution context that persists across asynchronous operations is called as zone
context. For example, the zone context will be same in both outside and inside
setTimeout callback function,
zone.run(() => {
// outside zone
expect(zoneThis).toBe(zone);
setTimeout(function() {
// the same outside zone exist here
expect(zoneThis).toBe(zone);
});
});
The current zone is retrieved through Zone.current.
What are the lifecycle hooks of a zone?
There are four lifecycle hooks for asynchronous operations from zone.js.
onScheduleTask: This hook triggers when a new asynchronous task is
scheduled. For example, when you call setTimeout()
onScheduleTask: function(delegate, curr, target, task) {
console.log('new task is scheduled:', task.type, task.source);
return delegate.scheduleTask(target, task);
}
onInvokeTask: This hook triggers when an asynchronous task is about to
execute. For example, when the callback of setTimeout() is about to execute.
onInvokeTask: function(delegate, curr, target, task, applyThis,
applyArgs) {
console.log('task will be invoked:', task.type, task.source);
return delegate.invokeTask(target, task, applyThis, applyArgs);
}
onHasTask: This hook triggers when the status of one kind of task inside a zone
changes from stable(no tasks in the zone) to unstable(a new task is scheduled in
the zone) or from unstable to stable.
onHasTask: function(delegate, curr, target, hasTaskState) {
console.log('task state changed in the zone:', hasTaskState);
return delegate.hasTask(target, hasTaskState);
}
onInvoke: This hook triggers when a synchronous function is going to execute
in the zone.
onInvoke: function(delegate, curr, target, callback, applyThis,
applyArgs) {
console.log('the callback will be invoked:', callback);
return delegate.invoke(target, callback, applyThis, applyArgs);
}
What are the methods of NgZone used to control change
detection?
NgZone service provides a run() method that allows you to execute a function
inside the angular zone. This function is used to execute third party APIs which
are not handled by Zone and trigger change detection automatically at the
correct time.
export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
ngOnInit() {
// use ngZone.run() to make the asynchronous operation in the
angular zone
this.ngZone.run(() => {
someNewAsyncAPI(() => {
// update the data of the component
});
});
}
}
Whereas runOutsideAngular() method is used when you don't want to trigger
change detection.
export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
ngOnInit() {
// Use this method when you know no data will be updated
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
// update component data and don't trigger change detection
});
});
}
}
How do you change the settings of zonejs?
You can change the settings of zone by configuring them in a separate file and
import it just after zonejs import. For example, you can disable the
requestAnimationFrame() monkey patch to prevent change detection for no data
update as one setting and prevent DOM events(a mousemove or scroll event) to
trigger change detection. Let's say the new file named zone-flags.js,
// disable patching requestAnimationFrame
(window as any).__Zone_disable_requestAnimationFrame = true;
// disable patching specified eventNames
(window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll',
'mousemove'];
The above configuration file can be imported in a polyfill.ts file as below,
/
********************************************************************
*******************************
* Zone JS is required by default for Angular.
*/
import `./zone-flags`;
import 'zone.js/dist/zone'; // Included with Angular CLI.
How do you trigger an animation?
Angular provides a trigger() function for animation in order to collect the states
and transitions with a specific animation name, so that you can attach it to the
triggering element in the HTML template. This function watch for changes and
trigger initiates the actions when a change occurs. For example, let's create
trigger named upDown, and attach it to the button element.
content_copy
@Component({
selector: 'app-up-down',
animations: [
trigger('upDown', [
state('up', style({
height: '200px',
opacity: 1,
backgroundColor: 'yellow'
})),
state('down', style({
height: '100px',
opacity: 0.5,
backgroundColor: 'green'
})),
transition('up => down', [
animate('1s')
]),
transition('down => up', [
animate('0.5s')
]),
]),
],
templateUrl: 'up-down.component.html',
styleUrls: ['up-down.component.css']
})
export class UpDownComponent {
isUp = true;
toggle() {
this.isUp = !this.isUp;
}
How do you configure injectors with providers at different
levels?
You can configure injectors with providers at different levels of your application
by setting a metadata value. The configuration can happen in one of three
places,
In the @Injectable() decorator for the service itself
In the @NgModule() decorator for an NgModule
In the @Component() decorator for a component
Is it mandatory to use injectable on every service class?
No. The @Injectable() decorator is not strictly required if the class has other
Angular decorators on it or does not have any dependencies. But the important
thing here is any class that is going to be injected with Angular is decorated. i.e,
If we add the decorator, the metadata design:paramtypes is added, and the
dependency injection can do it's job. That is the exact reason to add the
@Injectable() decorator on a service if this service has some dependencies itself.
For example, Let's see the different variations of AppService in a root
component,
The below AppService can be injected in AppComponent without any problems.
This is because there are no dependency services inside AppService.
export class AppService {
constructor() {
console.log('A new app service');
}
}
The below AppService with dummy decorator and httpService can be injected in
AppComponent without any problems. This is because meta information is
generated with dummy decorator.
function SomeDummyDecorator() {
return (constructor: Function) => console.log(constructor);
}
@SomeDummyDecorator()
export class AppService {
constructor(http: HttpService) {
console.log(http);
}
}
and the generated javascript code of above service has meta information about
HttpService, js var AppService = (function () { function AppService(http)
{ console.log(http); } AppService = __decorate([ core_1.Injectable(),
__metadata('design:paramtypes', [http_service_1.HttpService]) ],
AppService); return AppService; }()); exports.AppService = AppService; 3.
The below AppService with @injectable decorator and httpService can be
injected in AppComponent without any problems. This is because meta
information is generated with Injectable decorator. js
@Injectable({ providedIn: 'root', }) export class AppService
{ constructor(http: HttpService) { console.log(http); } }
What is an optional dependency?
The optional dependency is a parameter decorator to be used on constructor
parameters, which marks the parameter as being an optional dependency. Due
to this, the DI framework provides null if the dependency is not found. For
example, If you don't register a logger provider anywhere, the injector sets the
value of logger(or logger service) to null in the below class.
import { Optional } from '@angular/core';
constructor(@Optional() private logger?: Logger) {
if (this.logger) {
this.logger.log('This is an optional dependency message');
} else {
console.log('The logger is not registered');
}
}
What are the types of injector hierarchies?
There are two types of injector hierarchies in Angular
ModuleInjector hierarchy: It configure on a module level using an
@NgModule() or @Injectable() annotation.
ElementInjector hierarchy: It created implicitly at each DOM element. Also it
is empty by default unless you configure it in the providers property on
@Directive() or @Component().
What are reactive forms?
Reactive forms is a model-driven approach for creating forms in a reactive
style(form inputs changes over time). These are built around observable
streams, where form inputs and values are provided as streams of input values.
Let's follow the below steps to create reactive forms,
Register the reactive forms module which declares reactive-form directives in
your app
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
Create a new FormControl instance and save it in the component.
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'user-profile',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userName = new FormControl('');
}
Register the FormControl in the template.
<label>
User name:
<input type="text" [formControl]="userName">
</label>
Finally, the component with reactive form control appears as below, ```js import
{ Component } from '@angular/core'; import { FormControl } from
'@angular/forms';
@Component({
selector: 'user-profile',
styleUrls: ['./user-profile.component.css']
template: `
<label>
User name:
<input type="text" [formControl]="userName">
</label>
`
})
export class UserProfileComponent {
userName = new FormControl('');
}
```
What are dynamic forms?
Dynamic forms is a pattern in which we build a form dynamically based on
metadata that describes a business object model. You can create them based on
reactive form API.
What are template driven forms?
Template driven forms are model-driven forms where you write the logic,
validations, controls etc, in the template part of the code using directives. They
are suitable for simple scenarios and uses two-way binding with [(ngModel)]
syntax. For example, you can create register form easily by following the below
simple steps,
Import the FormsModule into the Application module's imports array
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'
import { RegisterComponent } from './app.component';n
@NgModule({
declarations: [
RegisterComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [RegisterComponent]
})
export class AppModule { }
Bind the form from template to the component using ngModel syntax
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name">
Attach NgForm directive to the tag in order to create FormControl instances and
register them
<form #registerForm="ngForm">
Apply the validation message for form controls
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Please enter your name
</div>
Let's submit the form with ngSubmit directive and add type="submit" button at
the bottom of the form to trigger form submit.
<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
// Form goes here
<button type="submit" class="btn btn-success" [disabled]="!
registerForm.form.valid">Submit</button>
Finally, the completed template-driven registration form will be appeared as
follow.
```html
<div class="container">
<h1>Registration Form</h1>
<form (ngSubmit)="onSubmit()" #registerForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Please enter your name
</div>
</div>
<button type="submit" class="btn btn-success" [disabled]="!
registerForm.form.valid">Submit</button>
</form>
</div>
```
What are the differences between reactive forms and
template driven forms?
Below are the main differences between reactive forms and template driven
forms
Feature Template-Driven Reactive
Form model Created(FormControl instance) in
Created by directives
setup component explicitly
Data updates Asynchronous Synchronous
Form custom
Defined as Directives Defined as Functions
validation
Need knowledge of the No interaction with change
Testing
change detection process detection cycle
Mutability Mutable(Property always Immutable(by always returning new
Feature Template-Driven Reactive
modified to new value) value for FormControl instance)
Less scalable using due to
Scalability More scalable using low-level APIs
abstraction on APIs
What are the different ways to group form controls?
Reactive forms provide two ways of grouping multiple related controls.
FormGroup: It defines a form with a fixed set of controls those can be managed
together in an one object. It has same properties and methods similar to a
FormControl instance. This FormGroup can be nested to create complex forms as
below.
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userProfile = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
onSubmit() {
// Store this.userProfile.value in DB
}
}
<form [formGroup]="userProfile" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div formGroupName="address">
<h3>Address</h3>
<label>
Street:
<input type="text" formControlName="street">
</label>
<label>
City:
<input type="text" formControlName="city">
</label>
<label>
State:
<input type="text" formControlName="state">
</label>
<label>
Zip Code:
<input type="text" formControlName="zip">
</label>
</div>
<button type="submit" [disabled]="!
userProfile.valid">Submit</button>
</form>
FormArray: It defines a dynamic form in an array format, where you can add
and remove controls at run time. This is useful for dynamic forms when you don’t
know how many controls will be present within the group.
import { Component } from '@angular/core';
import { FormArray, FormControl } from '@angular/forms';
@Component({
selector: 'order-form',
templateUrl: './order-form.component.html',
styleUrls: ['./order-form.component.css']
})
export class OrderFormComponent {
constructor () {
this.orderForm = new FormGroup({
firstName: new FormControl('John', Validators.minLength(3)),
lastName: new FormControl('Rodson'),
items: new FormArray([
new FormControl(null)
])
});
}
onSubmitForm () {
// Save the items this.orderForm.value in DB
}
onAddItem () {
this.orderForm.controls
.items.push(new FormControl(null));
}
onRemoveItem (index) {
this.orderForm.controls['items'].removeAt(index);
}
}
<form [formControlName]="orderForm" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div>
<p>Add items</p>
<ul formArrayName="items">
<li *ngFor="let item of orderForm.controls.items.controls; let i
= index">
<input type="text" formControlName="{{i}}">
<button type="button" title="Remove Item"
(click)="onRemoveItem(i)">Remove</button>
</li>
</ul>
<button type="button" (click)="onAddItem">
Add an item
</button>
</div>
How do you update specific properties of a form model?
You can use patchValue() method to update specific properties defined in the
form model. For example,you can update the name and street of certain profile
on click of the update button as shown below.
updateProfile() {
this.userProfile.patchValue({
firstName: 'John',
address: {
street: '98 Crescent Street'
}
});
}
<button (click)="updateProfile()">Update Profile</button>
You can also use setValue method to update properties.
Note: Remember to update the properties against the exact model structure.
What is the purpose of FormBuilder?
FormBuilder is used as syntactic sugar for easily creating instances of a
FormControl, FormGroup, or FormArray. This is helpful to reduce the amount of
boilerplate needed to build complex reactive forms. It is available as an
injectable helper class of the @angular/forms package.
For example, the user profile component creation becomes easier as shown
here.
export class UserProfileComponent {
profileForm = this.formBuilder.group({
firstName: [''],
lastName: [''],
address: this.formBuilder.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
});
constructor(private formBuilder: FormBuilder) { }
}
How do you verify the model changes in forms?
You can add a getter property(let's say, diagnostic) inside component to return a
JSON representation of the model during the development. This is useful to verify
whether the values are really flowing from the input box to the model and vice
versa or not.
export class UserProfileComponent {
model = new User('John', 29, 'Writer');
// TODO: Remove after the verification
get diagnostic() { return JSON.stringify(this.model); }
}
and add diagnostic binding near the top of the form
{{diagnostic}}
<div class="form-group">
// FormControls goes here
</div>
What are the state CSS classes provided by ngModel?
The ngModel directive updates the form control with special Angular CSS classes
to reflect it's state. Let's find the list of classes in a tabular format,
Form control state If true If false
Visited ng-touched ng-untouched
Value has
ng-dirty ng-pristine
changed
Value is valid ng-valid ng-invalid
How do you reset the form?
In a model-driven form, you can reset the form just by calling the
function reset() on our form model. For example, you can reset the form model
on submission as follows,
onSubmit() {
if (this.myform.valid) {
console.log("Form is submitted");
// Perform business logic here
this.myform.reset();
}
}
Now, your form model resets the form back to its original pristine state.
What are the types of validator functions?
In reactive forms, the validators can be either synchronous or asynchronous
functions,
Sync validators: These are the synchronous functions which take a control
instance and immediately return either a set of validation errors or null. Also,
these functions passed as second argument while instantiating the form control.
The main use cases are simple checks like whether a field is empty, whether it
exceeds a maximum length etc.
Async validators: These are the asynchronous functions which take a control
instance and return a Promise or Observable that later emits a set of validation
errors or null. Also, these functions passed as second argument while
instantiating the form control. The main use cases are complex validations like
hitting a server to check the availability of a username or email.
The representation of these validators looks like below
this.myForm = formBuilder.group({
firstName: ['value'],
lastName: ['value', *Some Sync validation function*],
email: ['value', *Some validation function*, *Some asynchronous
validation function*]
});
Can you give an example of built-in validators?
In reactive forms, you can use built-in validator like required and minlength on
your input form controls. For example, the registration form can have these
validators on name input field
this.registrationForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
])
});
Whereas in template-driven forms, both required and minlength validators
available as attributes.
How do you optimize the performance of async validators?
Since all validators run after every form value change, it creates a major impact
on performance with async validators by hitting the external API on each
keystroke. This situation can be avoided by delaying the form validity by
changing the updateOn property from change (default) to submit or blur. The
usage would be different based on form types,
Template-driven forms: Set the property on ngModelOptions directive
<input [(ngModel)]="name" [ngModelOptions]="{updateOn: 'blur'}">
Reactive-forms: Set the property on FormControl instance
name = new FormControl('', {updateOn: 'blur'});
How to set ngFor and ngIf on the same element?
Sometimes you may need to both ngFor and ngIf on the same element but
unfortunately you are going to encounter below template error.
Template parse errors: Can't have multiple template bindings on one
element.
In this case, You need to use either ng-container or ng-template. Let's say if you
try to loop over the items only when the items are available, the below code
throws an error in the browser
<ul *ngIf="items" *ngFor="let item of items">
<li></li>
</ul>
and it can be fixed by
<ng-container *ngIf="items">
<ul *ngFor="let item of items">
<li></li>
</ul>
</ng-container>
What is host property in css?
The :host pseudo-class selector is used to target styles in the element that hosts
the component. Since the host element is in a parent component's template, you
can't reach the host element from inside the component by other means. For
example, you can create a border for parent element as below,
//Other styles for app.component.css
//...
:host {
display: block;
border: 1px solid black;
padding: 20px;
}
How do you get the current route?
In Angular, there is an url property of router package to get the current route.
You need to follow the below few steps,
Import Router from @angular/router
import { Router } from '@angular/router';
Inject router inside constructor
constructor(private router: Router ) {
}
Access url parameter
console.log(this.router.url); // /routename
What is Component Test Harnesses?
A component harness is a testing API around an Angular directive or component
to make tests simpler by hiding implementation details from test suites. This can
be shared between unit tests, integration tests, and end-to-end tests. The idea
for component harnesses comes from the PageObject pattern commonly used
for integration testing.
What is the benefit of Automatic Inlining of Fonts?
During compile time, Angular CLI will download and inline the fonts that your
application is using. This performance update speed up the first contentful
paint(FCP) and this feature is enabled by default in apps built with version 11.
1. What is Angular? Why was it introduced?
Angular was introduced to create Single Page applications. This framework
brings structure and consistency to web applications and provides excellent
scalability and maintainability.
Angular is an open-source, JavaScript framework wholly written in TypeScript. It
uses HTML's syntax to express your application's components clearly.
2. What is TypeScript?
TypeScript is a superset of JavaScript that offers excellent consistency. It is
highly recommended, as it provides some syntactic sugar and makes the code
base more comfortable to understand and maintain. Ultimately, TypeScript code
compiles down to JavaScript that can run efficiently in any environment.
3. What is data binding? Which type of data binding does Angular deploy?
Data binding is a phenomenon that allows any internet user to manipulate Web
page elements using a Web browser. It uses dynamic HTML and does not require
complex scripting or programming. We use data binding in web pages that
contain interactive components such as forms, calculators, tutorials, and games.
Incremental display of a webpage makes data binding convenient when pages
have an enormous amount of data.
Angular uses the two-way binding. Any changes made to the user interface are
reflected in the corresponding model state. Conversely, any changes in the
model state are reflected in the UI state. This allows the framework to connect
the DOM to the Model data via the controller. However, this approach affects
performance since every change in the DOM has to be tracked.
4. What are Single Page Applications (SPA)?
Single-page applications are web applications that load once with new features
just being mere additions to the user interface. It does not load new HTML pages
to display the new page's content, instead generated dynamically. This is made
possible through JavaScript's ability to manipulate the DOM elements on the
existing page itself. A SPA approach is faster, thus providing a seamless user
experience.
5. Differentiate between Angular and AngularJS
The following table depicts the aspects of Angular vs AngularJS in detail:
Feature AngularJS Angular
Language JavaScript TypeScript
Supports Model-View-Controller
Architecture Uses components and directives
design
Not supported by mobile Supports all popular mobile
Mobile support
browsers browsers
Dependency
Doesn’t support Supports
Injection
@routeProvider is used to @Route configuration is used to
Routing
provide routing information define routing information
Difficult to manage with an Better structured, easy to create
Management
increase in source code size and manage bigger applications
6. What are decorators in Angular?
Decorators are a design pattern or functions that define how Angular features
work. They are used to make prior modifications to a class, service, or filter.
Angular supports four types of decorators, they are:
Class Decorators
Property Decorators
Method Decorators
Parameter Decorators
7. Mention some advantages of Angular.
Some of the common advantages of Angular are -
MVC architecture - Angular is a full-fledged MVC framework. It provides a firm
opinion on how the application should be structured. It also offers bi-directional
data flow and updates the real DOM.
Modules: Angular consists of different design patterns like components,
directives, pipes, and services, which help in the smooth creation of applications.
Dependency injection: Components dependent on other components can be
easily worked around using this feature.
Other generic advantages include clean and maintainable code, unit testing,
reusable components, data binding, and excellent responsive experience.
8. What are the new updates with Angular10?
Older versions of TypeScript not supported - Previous versions of Angular
supported typescript 3.6, 3.7, and even 3.8. But with Angular 10, TypeScript
bumped to TypeScript 3.9.
Warnings about CommonJS imports - Logging of unknown property bindings or
element names in templates is increased to the "error" level, which was
previously a "warning" before.
Optional strict setting - Version 10 offers a stricter project setup when you create
a new workspace with ng new command.
ng new --strict
NGCC Feature - Addition of NGCC features with a program based entry point
finder.
Updated URL routing
Deprecated APIs - Angular 10 has several deprecated APIs.
Bug fixes - With this Angular 10 version, there have been a number of bug fixes,
important ones being the compiler avoiding undefined expressions and the core
avoiding a migration error when a nonexistent symbol is imported.
New Default Browser Configuration - Browser configuration for new projects has
been upgraded to outdo older and less used browsers.
9. What are Templates in Angular?
Angular Templates are written with HTML that contains Angular-specific
elements and attributes. In combination with the model and controller's
information, these templates are further rendered to provide a dynamic view to
the user.
10. What are Annotations in Angular?
Annotations in Angular are used for creating an annotation array. They are the
metadata set on the class that is used to reflect the Metadata library.
11. What are Directives in Angular?
Directives are attributes that allow the user to write new HTML syntax specific to
their applications. They execute whenever the Angular compiler finds them in
the DOM. Angular supports three types of directives.
Component Directives
Structural Directives
Attribute Directives
12. What is an AOT compilation? What are its advantages?
The Ahead-of-time (AOT) compiler converts the Angular HTML and TypeScript
code into JavaScript code during the build phase, i.e., before the browser
downloads and runs the code.
Some of its advantages are as follows.
Faster rendering
Fewer asynchronous requests
Smaller Angular framework download size
Quick detection of template errors
Better security
13. What are Components in Angular?
Components are the basic building blocks of the user interface in an Angular
application. Every component is associated with a template and is a subset of
directives. An Angular application typically consists of a root component, which is
the AppComponent, that then branches out into other components creating a
hierarchy.
14. What are Pipes in Angular?
Pipes are simple functions designed to accept an input value, process, and return
as an output, a transformed value in a more technical understanding. Angular
supports several built-in pipes. However, you can also create custom pipes that
cater to your needs.
Some key features include:
Pipes are defined using the pipe “|” symbol.
Pipes can be chained with other pipes.
Pipes can be provided with arguments by using the colon (:) sign.
15. What is the PipeTransform interface?
As the name suggests, the interface receives an input value and transforms it
into the desired format with a transform() method. It is typically used to
implement custom pipes.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'demopipe'
})
export class DemopipePipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
return null;
}
16. What are Pure Pipes?
These pipes are pipes that use pure functions. As a result of this, a pure pipe
doesn't use any internal state, and the output remains the same as long as the
parameters passed stay the same. Angular calls the pipe only when it detects a
change in the parameters being passed. A single instance of the pure pipe is
used throughout all components.
17. What are Impure Pipes?
For every change detection cycle in Angular, an impure pipe is called regardless
of the change in the input fields. Multiple pipe instances are created for these
pipes. Inputs passed to these pipes can be mutable.
By default, all pipes are pure. However, you can specify impure pipes using the
pure property, as shown below.
@Pipe({ name: 'demopipe', pure : true/false })
export class DemopipePipe implements PipeTransform {
18. What is an ngModule?
NgModules are containers that reserve a block of code to an application domain
or a workflow. @NgModule takes a metadata object that generally describes the
way to compile the template of a component and to generate an injector at
runtime. In addition, it identifies the module's components, directives, and pipes,
making some of them public, through the export property so that external
components can use them.
19. What are filters in AngularJs? Name a few of them.
Filters are used to format an expression and present it to the user. They can be
used in view templates, controllers, or services. Some inbuilt filters are as
follows.
date - Format a date to a specified format.
filter - Select a subset of items from an array.
Json - Format an object to a JSON string.
limitTo - Limits an array/string, into a specified number of elements/characters.
lowercase - Format a string to lowercase.
20. What is view encapsulation in Angular?
View encapsulation defines whether the template and styles defined within the
component can affect the whole application or vice versa. Angular provides three
encapsulation strategies:
Emulated - styles from the main HTML propagate to the component.
Native - styles from the main HTML do not propagate to the component.
None - styles from the component propagate back to the main HTML and
therefore are visible to all components on the page.
21. What are controllers?
AngularJS controllers control the data of AngularJS applications. They are regular
JavaScript Objects. The ng-controller directive defines the application controller.
22. What do you understand by scope in Angular?
The scope in Angular binds the HTML, i.e., the view, and the JavaScript, i.e., the
controller. It as expected is an object with the available methods and properties.
The scope is available for both the view and the controller. When you make a
controller in Angular, you pass the $scope object as an argument.
24. What is String Interpolation in Angular?
String Interpolation is a one-way data-binding technique that outputs the data
from TypeScript code to HTML view. It is denoted using double curly braces. This
template expression helps display the data from the component to the view.
{{ data }}
25. What are Template statements?
Template statements are properties or methods used in HTML for responding to
user events. With these template statements, the application that you create or
are working on, can have the capability to engage users through actions such as
submitting forms and displaying dynamic content.
For example,
<button (click)="deleteHero()">Delete hero</button>
The template here is deleteHero. The method is called when the user clicks on
the button.
Advanced Level Questions
26. What is the difference between AOT and JIT?
Ahead of Time (AOT) compilation converts your code during the build time before
the browser downloads and runs that code. This ensures faster rendering to the
browser. To specify AOT compilation, include the --aot option with the ng build or
ng serve command.
The Just-in-Time (JIT) compilation process is a way of compiling computer code to
machine code during execution or run time. It is also known as dynamic
compilation. JIT compilation is the default when you run the ng build or ng serve
CLI commands.
27. Explain the @Component Decorator.
TypeScript class is one that is used to create components. This genre of class is
then decorated with the "@Component" decorator. The decorato’s purpose is to
accept a metadata object that provides relevant information about the
component.
The image above shows an App component - a pure TypeScript class decorated
with the “@Component” decorator. The metadata object that gets accepted by
the decorator provides properties like templateUrl, selector, and others, where
the templateUrL property points to an HTML file defining what you see on the
application.
28. What are Services in Angular?
Angular Services perform tasks that are used by multiple components. These
tasks could be data and image fetching, network connections, and database
management among others. They perform all the operational tasks for the
components and avoid rewriting of code. A service can be written once and
injected into all the components that use that service.
29. What are Promises and Observables in Angular?
While both the concepts deal with Asynchronous events in Angular, Promises
handle one such event at a time while observables handle a sequence of events
over some time.
Promises - They emit a single value at a time. They execute immediately after
creation and are not cancellable. They are Push errors to the child promises.
Observables - They are only executed when subscribed to them using the
subscribe() method. They emit multiple values over a period of time. They help
perform operations like forEach, filter, and retry, among others. They deliver
errors to the subscribers. When the unsubscribe() method is called, the listener
stops receiving further values.
30. What is ngOnInit? How is it defined?
ngOnInit is a lifecycle hook and a callback method that is run by Angular to
indicate that a component has been created. It takes no parameters and returns
a void type.
export class MyComponent implements OnInit {
constructor() { }
ngOnInit(): void {
//....
}
}
31. How to use ngFor in a tag?
The ngFor directive is used to build lists and tables in the HTML templates. In
simple terms, this directive is used to iterate over an array or an object and
create a template for each element.
<ul>
<li *ngFor = "let items in itemlist"> {{ item }} </li>
</ul>
“Let item” creates a local variable that will be available in the template
“Of items” indicates that we are iterating over the items iterable.
The * before ngFor creates a parent template.
32. What are Template and Reactive forms?
Template-driven approach
In this method, the conventional form tag is used to create forms. Angular
automatically interprets and creates a form object representation for the tag.
Controls can be added to the form using the NGModel tag. Multiple controls can
be grouped using the NGControlGroup module.
A form value can be generated using the “form.value” object. Form data is
exported as JSON values when the submit method is called.
Basic HTML validations can be used to validate the form fields. In the case of
custom validations, directives can be used.
Arguably, this method is the simplest way to create an Angular App.
Reactive Form Approach
This approach is the programming paradigm oriented around data flows and
propagation of change.
With Reactive forms, the component directly manages the data flows between
the form controls and the data models.
Reactive forms are code-driven, unlike the template-driven approach.
Reactive forms break from the traditional declarative approach.
Reactive forms eliminate the anti-pattern of updating the data model via two-
way data binding.
Typically, Reactive form control creation is synchronous and can be unit tested
with synchronous programming techniques.
33. What is Bootstrap? How is it embedded into Angular?
Bootstrap is a powerful toolkit. It is a collection of HTML, CSS, and JavaScript
tools for creating and building responsive web pages and web applications.
There are two ways to embed the bootstrap library into your application.
Angular Bootstrap via CDN - Bootstrap CDN is a public Content Delivery Network.
It enables you to load the CSS and JavaScript files remotely from its servers.
Angular Bootstrap via NPM - Another way to add Bootstrap to your Angular
project is to install it into your project folder by using NPM (Node Package
Manager).
npm install bootstrap
npm install jquery
34. What is Eager and Lazy loading?
Eager loading is the default module-loading strategy. Feature modules under
Eager loading are loaded before the application starts. This is typically used for
small size applications.
Lazy loading dynamically loads the feature modules when there's a demand. This
makes the application faster. It is used for bigger applications where all the
modules are not required at the start of the application.
35. What type of DOM does Angular implement?
DOM (Document Object Model) treats an XML or HTML document as a tree
structure in which each node is an object representing a part of the document.
Angular uses the regular DOM. This updates the entire tree structure of HTML
tags until it reaches the data to be updated. However, to ensure that the speed
and performance are not affected, Angular implements Change Detection.
1. What is Angular?
Angular is an open-source web application development framework created by
Google. It is used to build frontend, single-page applications that run on
JavaScript. It is a full-fledged framework, i.e., it takes care of many aspects of
frontend web applications such as HTTP requests, routing, layout, forms,
reactivity, validation, etc.
2. What are the technologies used in Angular?
Angular is a modern frontend JavaScript framework developed by Google.
Angular itself makes use of several technologies for several reasons to
accomplish certain tasks easily as well as to allow developers to have a better
experience while developing applications with it. Angular uses TypeScript, which
is a superscript of JavaScript. So, any valid JavaScript is a valid TypeScript.
However, TypeScript allows us to write JavaScript as a strongly typed language,
and we can define our own types as well, which makes catching bugs much
easier. It also uses RxJS, which allows developers to better deal with
asynchronous operations.
3. Why were client-side frameworks like Angular introduced?
Before JavaScript-based client-side frameworks, the way dynamic websites
worked was by taking a template that is nothing but HTML code with spaces left
empty for feeding data and content into those templates. This data was usually
fetched from a database. After combining the template and data, we would serve
the generated HTML content back to the user. As you can see, it was a bit
complicated, and in some cases, it took a lot of processing.
To overcome these issues, people came up with another approach in which they
send the necessary data to render a page from their web servers to the web
browsers and let JavaScript combine this data with a predefined template. Since
now, even mobile phones are powerful enough to do this kind of processing, the
servers can now just send the data to a client over the internet in a recognizable
format, i.e., JSON, XML, etc. This drastically reduces the processing done on the
servers and improves performance.
4. What is the difference between Angular and AngularJS?
Following are some of the major and significant differences between Angular and
AngularJS:
Features Angular AngularJS
Architecture It makes use of directives and It supports the Model-View-
components Controller or MVC model
Language It uses TypeScript language, a It uses JavaScript, a dynamically
superset of JavaScript that is typed language
typed statistically
Expression Angular uses () to bind an event It requires professionals to use
Syntax while [] to bind a property the correct ng directive to bind
a property or an event
Mobile Angular offers mobile support Unlike Angular, AngularJS does
Support not offer mobile support
Routing It uses @RouteConfig{(…)} It uses $routeprovider.when()
Dependency It supports hierarchical It does not support dependency
Injection dependency injection, along with injection
a unidirectional tree-based
change direction
Structure Its simplified structure makes it It is comparatively less
easy for professionals to develop manageable
and maintain large applications
easily
5. What are some advantages of using Angular?
Using Angular has several advantages, which are listed below:
Angular is built using TypeScript, which allows developers to write strongly typed
code that will get transpiled into JavaScript. The benefits of strongly typed code
are that it is easy to read, maintainable, and less prone to errors. Also, it
provides better tooling with type hints and code completion.
Angular allows us to separate our code into modules, which can be used to wrap
functionalities related to a specific task such as HTTP communication, data
validation, routing, etc.
Angular has a large ecosystem of tools, libraries, frameworks, plugins, etc. that
make the whole development experience much faster and enjoyable. These tools
and libraries include Angular CLI, RxJS, NgRx, etc.
Top of Form
Submit
Bottom of Form
7. What are some disadvantages of using Angular?
Although Angular provides quite a lot of benefits, there are some disadvantages
of using it as well. They are as follows:
Getting good SEO results on an Angular application can be a bit difficult and may
need a bit of configuration.
Angular has a lot of features packed into it, so getting to know each of them and
learning how to use them effectively together can be a little difficult.
Angular can add quite a lot of weight to your JavaScript bundle, so using it for
smaller projects can be very inefficient and may significantly increase the load
size.
8. What do you mean by string interpolation?
String interpolation in Angular, also known as the mustache syntax, only allows
one-way data binding. It is a special syntax that makes use of double curly
braces {{}} so that it can display the component data. Inside the braces are the
JavaScript expressions that Angular needs to execute to retrieve the result,
which can further be inserted into the HTML code. Moreover, as part of the digest
cycle, these expressions are regularly updated and stored.
9. What are the differences between Angular decorator and annotation?
In Angular, decorators are design patterns that help in the modification or
decoration of the respective classes without making changes in the actual source
code.
Annotations, on the other hand, are used in Angular to build an annotation array.
They use the Reflective Metadata library and are a metadata set of the given
class.
11. What are the advantages of AOT?
AOT compilation has several advantages as mentioned below:
Fast rendering: Since, after compilation, the browser would download a pre-
compiled version of our application, it can render the application immediately
without compiling the app.
Less asynchronous requests: It takes external HTML templates and CSS style
sheets and inlines them within the application JavaScript, which reduces the
number of separate Ajax requests.
Smaller download size: The compiler will minify the code for us so that the
download size is less.
Template error detection: During the compilation phase, any issues in the
templates will be detected and reported by the compiler so that they can be
corrected before production.
12. What are the components in Angular?
Components are the basic building block of the user interface in Angular. A
component consists of HTML, CSS, and JavaScript for a specific portion of a user
interface. We can think of these as a custom HTML element that only Angular
can understand. These components are isolated, i.e., styles and code from one
component do not affect other components as they get namespaced by the
compiler. These components are then pieced together by the Angular framework
to build the user interface for the browser to render.
13. What are modules in Angular?
A module is a logical boundary of our application. It is used to encapsulate code
dealing with a specific aspect of the application, such as routing, HTTP,
validation, etc. The main reason why modules are used is to enhance application
composability. For example, if we wish to implement validation logic using
different libraries, then for the one we have already implemented, we can create
a new validation module and replace the current one with the new one, and our
application would work just the same. In Angular, we create a module using the
NgModule decorator.
14. What is DOM?
The full form of DOM is Document Object Model, and it is responsible for
representing the content of a web page and changes in the architecture of an
application. Here, all the objects are organized in the form of a tree, and the
document can easily be modified, manipulated, and accessed only with the help
of APIs.
15. What are services in Angular?
A service in Angular is a term that covers broad categories of functionalities. A
service is any value, function, or feature that an app needs. A service is typically
used to accomplish a very narrow purpose such as HTTP communication, sending
data to a cloud service, decoding some text, validating data, etc. A service does
one thing and does it well. It is different from a component as it is not concerned
with HTML or any other kind of presentation logic. Normally, a component uses
multiple services to accomplish multiple tasks.
16. What is the difference between jQuery and Angular?
The main difference between jQuery and Angular is that jQuery is a JS library,
whereas Angular is a JS frontend framework. Some of the other differences
between the two are mentioned below:
Unlike jQuery, Angular offers two-way data binding
Unlike Angular, jQuery does not offer support for the RESTful API
Angular supports deep linking routing, while jQuery does not
Form validation is available in Angular but not in jQuery
Although they have their differences, Angular and jQuery also have their set of
similarities, like both jQuery and Angular expressions consist of variables,
operators, and literals.
17. What are lifecycle hooks in Angular?
When building an Angular app, there will be times when we need to execute
some code at some specific event—such as when a component is initialized or
displayed on the screen or when the component is being removed from the
screen. This is what lifecycle hooks are used for. For example, if we have some
event listener attached to an HTML element in a component, such as a button
click or form submission, we can remove that event listener before removing the
component from the screen, just like we can fetch some data and display it on
the screen in a component after the component is loaded on the screen. To use a
lifecycle hook, we can override some methods on a component, such as ngOnInit
or ngAfterViewInit. These methods, if available on a component, will be called by
Angular automatically. This is why these are called lifecycle hooks.
18. What are templates?
Angular templates are written using HTML that includes attributes and elements
that are specific to Angular. The templates are further combined with the data
from the controller and the model, which can be rendered to offer the user a
dynamic view.
19. What is a two-way data binding?
Two-way data binding is done in Angular to ensure that the data model is
automatically synchronized in the view. For example, when a user updates some
data in a model and that model is being displayed in multiple places in a
component, that update should be reflected in all the places.
Two-way data binding has been supported in Angular for a long time. Although, it
is something that should be used with careful consideration as it could lead to
poor application performance or performance degradation as time goes on. It is
called two-way data binding because we can change some data that is in the
component model from the view that is HTML, and that change can also
propagate to all other places in the view where it is displayed.
20. What are pipes in Angular?
When we are trying to output some dynamic data in our templates, we may
sometimes need to manipulate or transform the data before it is put into our
templates. Though there are several ways of doing that, in Angular, using pipes
is the most preferred way. A pipe is just a simple function, which we can use with
expressions in our templates.
Pipes are extremely useful as we can use them throughout our application after
declaring them just once and registering them with the Angular framework.
Some of the most common built-in pipes in Angular are UpperCasePipe,
LowerCasePipe, CurrencyPipe, etc.
21. What are observables in Angular?
An observable is a declarative way using which we can perform asynchronous
tasks. Observables can be thought of as streams of data flowing from a publisher
to a subscriber. They are similar to promises as they both deal with handling
asynchronous requests. However, observables are considered to be a better
alternative to promises as the former comes with a lot of operators that allow
developers to better deal with asynchronous requests, especially if there is more
than one request at a time.
Observables are preferred by many developers as they allow them to perform
multiple operations such as combining two observables, mapping an observable
into another observable, and even piping multiple operations through an
observable to manipulate its data.
22. How are observables different from promises?
Although both promises and observables are used to handle asynchronous
requests in JavaScript, they work in very different ways. Promises can only
handle a single event at a time, while observables can handle a sequence of
asynchronous events over a period of time. Observables also provide us with a
wide variety of operators that allow us to transform data flowing through these
observables with ease.
A promise is just a way to wrap asynchronous operations so that they can be
easily used, while an observable is a way to turn asynchronous operations into a
stream of data that flows from a publisher to a subscriber through a well-defined
path with multiple operations transforming the data along the way.
23. What does Angular Material mean?
Angular Material is a UI component library that allows professionals to develop
consistent, attractive, and completely functional websites, web pages, and web
applications. It becomes capable of doing so by following modern principles of
web designing, such as graceful degradation and browser probability.
24. What is RxJS?
RxJS is a library, and the term stands for Reactive Extensions for JavaScript. It is
used so that we can use observables in our JavaScript project, which enables us
to perform reactive programming. RxJS is used in many popular frameworks such
as Angular because it allows us to compose our asynchronous operations or
callback-based code into a series of operations performed on a stream of data
that emits values from a publisher to a subscriber. Other languages such as Java,
Python, etc. also have libraries that allow them to write reactive code using
observables.
Angular Intermediate Interview Questions
25. What is bootstrapping?
Angular bootstrapping, in simple words, allows professionals to initialize or start
the Angular application. Angular supports both manual and automatic
bootstrapping. Let’s briefly understand the two.
Manual bootstrapping: It gives more control to professionals with regards to how
and when they need to initialize the Angular app. It is extremely useful in places
where professionals wish to perform other tasks and operations before the
Angular compiles the page.
Automatic bootstrapping: Automatic bootstrapping can be used to add the ng-
app directive to the application’s root, often on the tag if professionals need
Angular to automatically bootstrap the application. Angular loads the associated
module once it finds the ng-app directive and, further, compiles the DOM.
26. What do you mean by dependency injection?
Dependency injection (DI) in Angular is a software design pattern in which the
objects can be passed in the form of dependencies instead of hard-coding them
in the respective components. This concept is extremely handy when it comes to
separating the object logic creation from its consumption.
The function ‘config’ uses DI that needs to be configured so that the module can
be loaded to retrieve the application elements. Besides, this feature allows
professionals to change dependencies based on necessities.
27. What are Angular building blocks?
The following building blocks play a crucial role in Angular:
Components: A component can control numerous views wherein each of the
views is a particular part on the screen. All Angular applications have a minimum
of one component called the root component. This component is bootstrapped in
the root module, the main module. All the components include the logic of the
application that is defined in a class, while the main role of the class is to interact
with the view using an API of functions and properties.
Data binding: Data binding is the process in which the various sections of a
template interact with the component. The binding markup needs to be added to
the HTML template so that Angular can understand how it can connect with the
component and template.
Dependency injection: It uses DI so that it can offer the necessary dependencies,
mainly services, to the new components. The constructor parameters of a
component inform Angular regarding the numerous services needed by the
component, and DI provides a solution that gives the necessary dependencies to
the new class instances.
Directives: Angular templates are of dynamic nature, and directives help Angular
understand how it can transform the DOM while manifesting the template.
Metadata: Classes have metadata attached to them with the help of decorators
so that Angular will have an idea of processing the class.
Modules: Module or NgModule is a block of code organized using the necessary
capabilities set, having one specific workflow. All Angular applications have at
least one module, the root module, and most of the applications have numerous
modules.
Routing: Angular router helps interpret the URL of a browser to get a client-
generated experience and view. This router is bound to page links so that
Angular can go to the application view as soon as the user clicks on it.
Services: Service is a vast category that ranges from functions and values to
features that play a significant role in Angular application.
Template: The view of each component is linked with a template, and an Angular
template is a type of HTML tag that allows Angular to get an idea of how it needs
to render the component.
28. Explain the MVVM architecture.
The MVVM architecture plays a significant role in eliminating tight coupling
between the components. This architecture includes the following three parts:
Model: The model represents the business logic and data of a particular
application. In other words, it consists of an entity structure. The model has the
business logic, including model classes, remote and local data sources, and the
repository.
View: View is the application’s visual layer that comprises the UI code. The view
sends the action of the user to the ViewModel. However, it does not receive the
response directly. The view must subscribe to the observables that are exposed
to it by the ViewModel to receive a response.
ViewModel: ViewModel is the application’s abstract layer that connects the View
and the Model and acts as a bridge between the two. It does not know which
View needs to be made use of since it does not have any direct access to the
View. The two are connected using data binding, and the ViewModel records all
the changes that are made to the View and makes the necessary changes to the
Model.
29. Describe Angular authentication and authorization.
The login details of a user are given to an authenticate API available on the
server. Once the credentials are validated by the server, it returns a JSON web
token (JWT), which includes attributes and the data of the current user. Further,
the user is easily identified using JWT, and this process is known as
authentication.
After logging in, users have various types and levels of access—some can access
everything, while others may have restrictions from some resources.
Authorization determines the access level of these users.
30. What is the digest cycle process in Angular?
Digest cycle in Angular is the process in which the watchlist is monitored to track
changes in the watch variable value. In each digest cycle, there is a comparison
between the present and the previous versions of the scope model values.
31. What are the distinct types of Angular filters?
Filters are a part of Angular that helps in formatting the expression value to show
it to the user. They can be added to services, directives, templates, or
controllers. You also have the option to create personalized filters as per
requirements. These filters allow you to organize the data easily such that only
the data that meets the respective criteria are displayed. Filters are placed after
the pipe symbol ( | ) while used in expressions.
Various types of filters in Angular are mentioned below:
currency: It converts numbers to the currency format
filter: It selects a subset containing items from the given array
date: It converts a date into a necessary format
lowercase: It converts the given string into lowercase
uppercase: It converts the given string into uppercase
orderBy: It arranges an array by the given expression
json: It formats any object into a JSON string
number: It converts a number value into a string
limitTo: It restricts the limit of a given string or array to a particular number of
elements or strings
32. How can one create a service in Angular?
Service in Angular is an object that can be substituted. It is wired and combined
with the help of dependency injection. Services are developed by getting
registered in a module that they need to be executed in. The three methods of
creating a service in Angular are as follows:
Service
Factory
Provider
Angular Advanced Interview Questions
Let’s start with the advanced Angular interview questions and answers for
experienced users.
33. What does subscribing mean in RxJS?
In RxJS, when using observables, we need to subscribe to an observable to use
the data that flows through that observable. This data is generated from a
publisher and is consumed by a subscriber. When we subscribe to an observable,
we pass in a function for the data and another function for errors so that, in case
there is some error, we can show some message or process the message in
some way.
34. What is Angular Router?
Routing in a single-page frontend application is the task of responding to the
changes in the URL made by adding and removing content from the application.
This is a complicated task as we first need to intercept a request that changes
the browser’s URL as we do not wish for the browser to reload. Then, we need to
determine which content to remove and which content to add, and finally, we
have to change the browser’s URL as well to show the user the current page they
are on.
As we can see, this can be very difficult to implement, especially in multiple
applications. That is why Angular comes with a full routing solution for a single-
page application. In this, we can define routes with matching components and let
Angular handle the routing process.
35. What is REST?
REST in Angular stands for Representational State Transfer. It is an API that
works on the request of HTTP. Here, the requested URL points to the data that
has to be processed, after which an HTTP function is used to identify the
respective operation that has to be performed on the data given. The APIs that
follow this method are referred to as RESTful APIs.
36. What is the scope?
A scope is an object in Angular referring to the application model. It is a context
for executing expressions. These scopes are organized in a hierarchical form that
is similar to the application’s DOM structure. A scope helps in propagating
various events and watching expressions.
37. Explain Angular CLI.
Angular CLI is otherwise known as Angular command-line interface. Angular
supports CLI tools that give professionals the ability to use them to add
components, deploy them instantly, and perform testing and many such
functions.
38. What is HttpClient, and what are its benefits?
HttpClient is an Angular module used for communicating with a backend service
via the HTTP protocol. Usually, in frontend applications, for sending requests, we
use the fetch API. However, the fetch API uses promises. Promises are useful, but
they do not offer the rich functionalities that observables offer. This is why we
use HttpClient in Angular as it returns the data as an observable, which we can
subscribe to, unsubscribe to, and perform several operations on using operators.
Observables can be converted to promises, and an observable can be created
from a promise as well.
39. What is multicasting in Angular?
In Angular, when we are using the HttpClient module to communicate with a
backend service and fetch some data, after fetching the data, we can broadcast
it to multiple subscribers, all in one execution. This task of responding with data
to multiple subscribers is called multicasting. It is specifically useful when we
have multiple parts of our applications waiting for some data. To use
multicasting, we need to use an RxJS subject. As observables are unicast, they
do not allow multiple subscribers. However, subjects do allow multiple
subscribers and are multicast.
40. What is a directive in Angular?
A directive in Angular is used to extend the syntax and capabilities of a normal
HTML view. Angular directives have special meaning and are understood by the
Angular compiler. When Angular begins compiling the TypeScript, CSS, and HTML
files into a single JavaScript file, it scans through the entire code and looks for a
directive that has been registered. In case it finds a match, then the compiler
changes the HTML view accordingly.
Angular is shipped with many directives. However, we can build our directives
and let Angular know what they do so that the compiler knows about them and
uses them during the compilation step.
41. What is the role of SPA in Angular?
SPA stands for Single Page Application. This technology only maintains one page,
index.HTML, even when the URL changes constantly. SPA technology is easy to
build and extremely fast in comparison to traditional web technology.
42. Explain different kinds of Angular directives.
There are three kinds of directives in Angular. Let’s discuss them:
Components: A component is simply a directive with a template. It is used to
define a single piece of the user interface using TypeScript code, CSS styles, and
the HTML template. When we define a component, we use the component
decorated with the @ symbol and pass in an object with a selector attribute. The
selector attribute gives the Angular compiler the HTML tag that the component is
associated with so that, now, when it encounters this tag in HTML, it knows to
replace it with the component template.
Structural: Structural directives are used to change the structure of a view. For
example, if we wish to show or hide some data based on some property, we can
do so by using the ngIf directive, or if we wish to add a list of data in the markup,
we can use *ngFor, and so on. These directives are called structural directives
because they change the structure of the template.
Attribute: Attribute directives change the appearance or behavior of an
element, component, or another directive. They are used as the attributes of
elements. Directives such as ngClass and ngStyle are attribute directives.
43. What are the different types of compilers used in Angular?
In Angular, we use two different kinds of compilers:
Just-in-time (JIT) compiler
Ahead-of-time (AOT) compiler
Both these compilers are useful but for quite different purposes. The JIT compiler
is used to compile TypeScript to JavaScript as our browsers cannot understand
TypeScript but only JavaScript. This compilation step is done in a development
environment, i.e., when less time is needed to be spent on compilation and more
in development to quickly iterate over features. The JIT compiler is used when we
use ng serve or ng build command to serve the app locally or create an
uncompressed build of the entire codebase.
On the other hand, the AOT compiler is used to create a minified production build
of the entire codebase, which can be used in production. To use the AOT
compiler, we have to use the ng build command with the –prod blog: ng build –
prod. This instructs the Angular CLI to create an optimized production build of
the codebase. This takes a bit more time because several optimizations such as
minification can take time, but for production builds, this time can be spared.
44. What is the purpose of the common module in Angular?
In Angular, the common module that is available in the package
@angualr/common is a module that encapsulates all the commonly needed
features of Angular, such as services, pipes, directives, etc. It contains some sub-
modules as well such as the HttpClientModule, which is available in the
@angular/common/http package. Because of the modular nature of Angular, its
functionalities are stored in small self-contained modules, which can be imported
and included in our projects if we need these functionalities.
45. What are the differences between AngularJS and Angular?
AngularJS is the previous version of Angular, which is a complete rewrite, i.e.,
there are several differences between the two that we can highlight.
Architecture: AngularJS supports the MVC architecture in which the model
contains the business logic; the view shows the information fetched from the
models, and the controller manages interactions between the view and the
model by fetching data from the model and passing it to the view. On the other
hand, in Angular, we have a component-based architecture where instead of
having separate pieces for logic, presentation, etc., we now have a single self-
contained piece of the user interface that can be used in isolation or included in
a big project.
Language: In AngularJS, we could only use JavaScript. However, in Angular, we
can use both TypeScript and JavaScript.
Mobile support: In AngularJS, we do not get mobile browser support out of the
box, but in Angular, we do get mobile support for all popular mobile browsers.
46. What are the differences between Angular expressions and
JavaScript expressions?
Angular expressions and JavaScript expressions are quite different from each
other as, in Angular, we are allowed to write JavaScript in HTML, which we cannot
do in plain JavaScript. Also, all expressions in Angular are scoped locally. But, in
JavaScript, these expressions are scoped against the global window object. These
differences, however, are reconciled when the Angular compiler takes the
Angular code we have written and converts it into plain JavaScript, which can
then be understood and used by a web browser.
47. What is server-side rendering in Angular?
In a normal Angular application, the browser executes our application, and
JavaScript handles all the user interactions. However, because of this,
sometimes, if we have a large application with a big bundle size, our page’s load
speed is slowed down quite a bit as it needs to download all the files, parse
JavaScript, and then execute it. To overcome this slowness, we can use server-
side rendering, which allows us to send a fully rendered page from the server
that the browser can display and then let the JavaScript code take over any
subsequent interactions from the user.
48. What is Angular Universal?
Angular Universal is a package for enabling server-side rendering in Angular
applications. We can easily make our application ready for server-side rendering
using the Angular CLI. To do this, we need to type the following command:
ng add @nguniversal/express-engine
This allows our Angular application to work well with an ExpressJS web server
that compiles HTML pages with Angular Universal based on client requests. This
also creates the server-side app module, app.server.module.ts, in our application
directory.
49. What is the difference between interpolated content and the
content assigned to the innerHTML property of a DOM element?
Angular interpolation happens when in our template we type some JavaScript
expression inside double curly braces ‘{{ someExpression() }}’. This is used to
add dynamic content to a web page. However, we can do the same by assigning
some dynamic content to the innerHTML property of a DOM element. The
difference between the two is that, in Angular, the compiler always escapes the
interpolated content, i.e., HTML is not interpreted, and the browser displays the
code as it is with brackets and symbols, rather than displaying the output of the
interpreted HTML. However, in innerHTML, if the content is HTML, then it is
interpreted as the HTML code.
50. What are HttpInterceptors in Angular?
HttpInterceptors are part of the @angular/common/http module and are used to
inspect and transform HTTP requests and HTTP responses as well. These
interceptors are created to perform checks on a request, manipulate the
response, and perform cross-cutting concerns, such as logging requests,
authenticating a user using a request, using gzip to compress the response, etc.
If you have any doubts or queries related to Angular, get them clarified
from the AngularJs experts on our Web Development Community!
Hopefully, these Angular interview questions in 2021 have helped you get a
better grasp of Angular as a framework, as well as its various features and
capabilities. These frequently asked questions have been created to give you a
better understanding of the kinds of questions asked in interviews, so they will
help you in understanding Angular interviews and Angular as a framework. These
Angular interview questions with their answers might have whetted your
appetite for learning more about the framework. They will surely help you to ace
your next job interview.
9. What is the use of CORS?
CORS stands for Cross-origin Resource Sharing. It is a mechanism that allows a
variety of resources to be requested at a time from a domain that is outside the
current request domain.
The next web application interview question comprises an important difference.
Check it out below.
Question: What is Angular?
Answer: Angular is a TypeScript-based open-source web application framework,
developed and maintained by Google. It offers an easy and powerful way of
building front end web-based applications.
Angular integrates a range of features like declarative templates, dependency
injection, end-to-end tooling, etc. that facilitates web application development.
Question: Why was Angular introduced as a client-side framework?
Answer: Traditionally, VanillaJS and jQuery were used by developers to develop
dynamic websites. As the websites became more complex with added features
and functionality, it was hard for the developers to maintain the code. Moreover,
there was no provision of data handling facilities across the views by jQuery. So,
Angular was built to address these issues, thus, making it easier for the
developers by dividing code into smaller bits of information that are known as
Components in Angular.
Client-side frameworks permit the development of advanced web applications
like SPAs which, if developed by VanillaJS, is a slower process .
Question: Define the ng-content Directive?
Answer: Conventional HTML elements have some content between the tags. For
instance:
<p>Put your paragraph here</p>
Now consider the following example of having custom text between angular tags:
<app-work>This won’t work like HTML until you use ng-content
Directive</app-work>
However, doing so won’t work the way it worked for HTML elements. In order to
make it work just like the HTML example mentioned above, we need to use the ng-
content Directive. Moreover, it is helpful in building reusable components.
Know more about the ng-content directive.
Question: Please explain the various features of Angular.
Answer: There are several features of Angular that make it an ideal front end
JavaScript framework. Most important of them are described as follows:
Accessibility Applications
Angular allows creating accessible applications using ARIA-enabled components,
built-in a11y test infrastructure, and developer guides.
Angular CLI
Angular provides support for command-line interface tools. These tools can be
used for adding components, testing, instant deploying, etc.
Animation Support
Angular’s intuitive API allows the creation of high-performance, complex
animation timelines with very little code.
Cross-Platform App Development
Angular can be used for building an efficient and powerful desktop, native, and
progressive web apps. Angular provides support for building native mobile
applications using Cordova, Ionic, or NativeScript.
Angular allows creating high performance, offline, and zero-step installation
progressive web apps using modern web platform capabilities. The popular JS
framework can also be used for building desktop apps for Linux, macOS, and
Windows.
Code Generation
Angular is able to convert templates into highly-optimized code for modern
JavaScript virtual machines.
Code Splitting
With the new Component Router, Angular apps load quickly. The Component
Router offers automatic code-splitting so that only the code required to render
the view that is requested by a user is loaded.
Synergy with Popular Code Editors and IDEs
Angular offers code completion, instant errors, etc. with popular source code
editors and IDEs.
Templates
Allows creating UI views with a simple and powerful template syntax.
Testing
Angular lets you carry out frequent unit tests using Karma. The Protractor allows
running faster scenario tests in a stable way.
Question: State some advantages of Angular over other frameworks.
Answer:
Out of box Features: Several built-in features like routing, state management,
rxjs library, and HTTP services are straight out of the box services provided by
Angular. So, one does not need to look for the above-stated features separately.
Declarative UI: Angular uses HTML to render the UI of an application as it is a
declarative language and is much easier to use than JavaScript.
Long-term Google Support: Google plans to stick with Angular and further scale
up its ecosystem as it has offered its long term support to Angular.
Question: What is the difference between Angular and AngularJS.
Answer:
Parameters AngularJS Angular
MVC or Model-View-Controller
architecture facilitates the AngularJS
framework, where the Model contains Angular replaces controllers with
Architecture the business logic and Controllers Components that are directives
processes information, lastly, View with a predefined template.
shows the information present in the
Model.
Angular uses TypeScript
language, a statically typed
AngularJS uses JavaScript language, language, and a superset of
Language
which is a dynamically typed language. JavaScript. Angular provides
better performance while
developing larger applications.
Supported by all popular mobile
Mobile Support Does not support mobile support.
browsers.
The process of maintaining code It is easier to maintain code for
Structure becomes tedious in the case of larger larger applications as it provides
applications. a better structure.
A developer needs to remember the Property binding is done using "
Expression Syntax correct ng-directive for binding an event ]" attribute and event binding is
or a property. done using "( )" attribute.
Angular uses
Routing AngularJS uses $routeprovider.when()
@RouteConfig{(…)}
The development effort and time are
Angular is faster due to
Speed reduced significantly because of the
upgraded features.
two-way data binding
Angular supports a hierarchical
Dependency Injectio Dependency Injection with
AngularJS doesn’t support DI.
n unidirectional tree-based change
detection.
Angular has active support with
No official support or updates are
Support updates rolling out every now
available for AngularJS.
and then.
Question: Could we make an angular application to render on the server-
side?
Answer: Yes, we can, with Angular Universal, a technology provided by Angular
capable of rendering applications on the server-side.
The benefits of using Angular Universal are:
Better User Experience: Allows users to see the view of the application instantly.
Better SEO: Universal ensures that the content is available on every search
engine leading to better SEO.
Loads Faster: Render pages are available to the browsers sooner, so the server-
side application loads faster.
Question: Explain Dependency Injection?
Answer: Dependency injection is an application design pattern that is implemented
by Angular and forms the core concepts of Angular.
Let us understand in a detailed manner. Dependencies in Angular are services which
have a functionality. Various components and directives in an application can need
these functionalities of the service. Angular provides a smooth mechanism by which
these dependencies are injected into components and directives.
Question: Describe the MVVM architecture.
Answer: MVVM architecture removes tight coupling between each component. The
MVVM architecture comprises of three parts:
Model
View
ViewModel
The architecture allows the children to have reference through observables and not
directly to their parents.
Model: It represents the data and the business logic of an application, or we may say
it contains the structure of an entity. It consists of the business logic - local and
remote data source, model classes, repository.
View: View is a visual layer of the application, and so consists of the UI Code(in
Angular- HTML template of a component.). It sends the user action to the ViewModel
but does not get the response back directly. It has to subscribe to the observables
which ViewModel exposes to it to get the response.
ViewModel: It is an abstract layer of the application and acts as a bridge between the
View and Model(business logic). It does not have any clue which View has to use it
as it does not have a direct reference to the View. View and ViewModel are
connected with data-binding so, any change in the View the ViewModel takes note
and changes the data inside the Model. It interacts with the Model and exposes the
observable that can be observed by the View.
Question: Demonstrate navigating between different routes in an Angular
application.
Answer: Following code demonstrates how to navigate between different routes in
an Angular app dubbed “Some Search App”:
import from "@angular/router";
.
.
.
@Component({
selector: 'app-header',
template: `
<nav class="navbar navbar-light bg-faded">
<a class="navbar-brand" (click)="goHome()">Some Search App</a>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" (click)="goHome()">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" (click)="goSearch()">Search</a>
</li>
</ul>
</nav>
`
})
class HeaderComponent {
constructor(private router: Router) {}
goHome() {
this.router.navigate(['']);
}
goSearch() {
this.router.navigate(['search']);
}
}
Question: What is the AOT (Ahead-Of-Time) Compilation? What are its
advantages?
Answer: An angular application consists of components and templates which a
browser cannot understand. Therefore, every Angular application needs to be
compiled before running inside the browser. The Angular compiler takes in the JS
code, compiles it, and then produces some JS code. It is known as AOT compilation
and happens only once per occasion per user.
There are two kinds of compilation that Angular provides:
JIT(Just-in-Time) compilation: the application compiles inside the browser during
runtime
AOT(Ahead-of-Time) compilation: the application compiles during the build time.
Advantages of AOT compilation:
Fast Rendering: The browser loads the executable code and renders it immediately
as the application is compiled before running inside the browser.
Fewer Ajax Requests: The compiler sends the external HTML and CSS files along
with the application, eliminating AJAX requests for those source files.
Minimizing Errors: Easy to detect and handle errors during the building phase.
Better Security: Before an application runs inside the browser, the AOT compiler
adds HTML and templates into the JS files, so there are no extra HTML files to be
read, thus providing better security for the application.
Question: Could you explain services in Angular?
Answer: Singleton objects in Angular that get instantiated only once during the
lifetime of an application are called services. An Angular service contains
methods that maintain the data throughout the life of an application.
The primary intent of an Angular service is to organize as well as share business
logic, models, or data and functions with various components of an Angular
application.
The functions offered by an Angular service can be invoked from any Angular
component, such as a controller or directive.
Question: Discuss the advantages and disadvantages of using Angular?
Answer: Following are the various advantages of using Angular:
Ability to add a custom directive
Exceptional community support
Facilitates client and server communication
Features strong features, such as Animation and Event Handlers
Follows the MVC pattern architecture
Offers support for static template and Angular template
Support for two-way data-binding
Supports dependency injection, RESTful services, and validations
Disadvantages of using Angular are enumerated as follows:
Complex SPAs can be inconvenient and laggy to use due to their size
Dynamic applications do not always perform well
Learning Angular requires a decent effort and time
Question: Enumerate some salient features of Angular 7.
Answer: Unlike the previous versions of Angular, the 7th major release comes with
splitting in @angular/core. This is done in order to reduce the size of the same.
Typically, not each and every module is required by an Angular developer.
Therefore, in Angular 7 each split of the @angular/core will have no more than 418
modules.
Also, Angular 7 brings drag-and-drop and virtual scrolling into play. The latter
enables loading as well as unloading elements from the DOM. For virtual scrolling,
the latest version of Angular comes with the package. Furthermore, Angular 7 comes
with a new and enhanced version of the ng-compiler.
Question: What is string interpolation in Angular?
Answer: Also referred to as moustache syntax, string interpolation in Angular refers
to a special type of syntax that makes use of template expressions in order to display
the component data. These template expressions are enclosed within double curly
braces i.e. {{ }}.
The JavaScript expressions that are to be executed by Angular are added within the
curly braces and the corresponding output is embedded into the HTML code.
Typically, these expressions are updated and registered like watches as a part of the
digest cycle.
Question: Explain Angular Authentication and Authorization.
Answer: The user login credentials are passed to an authenticate API, which is
present on the server. Post server-side validation of the credentials, a JWT (JSON
Web Token) is returned. The JWT has information or attributes regarding the current
user. The user is then identified with the given JWT. This is called authentication.
Post logging-in successfully, different users have a different level of access. While
some may access everything, access for others might be restricted to only some
resources. The level of access is authorization.
Here is a detailed post on Angular 7 - JWT Authentication Example & Tutorial:
http://jasonwatmore.com/post/2018/11/16/angular-7-jwt-authentication-example-
tutorial
Question: Can you explain the concept of scope hierarchy in Angular?
Answer: Angular organizes the $scope objects into a hierarchy that is typically used
by views. This is known as the scope hierarchy in Angular. It has a root scope that
can further contain one or several scopes called child scopes.
In a scope hierarchy, each view has its own $scope. Hence, the variables set by a
view’s view controller will remain hidden to other view controllers. Following is a
typical representation of a Scope Hierarchy:
Root $scope
$scope for Controller 1
$scope for Controller 2
…
..
.
$scope for Controller n
Question: How to generate a class in Angular 7 using CLI?
Answer:
ng generate class Dummy [options]
This will generate a class named Dummy.
Question: Explain what is the difference between Angular
and backbone.js?
Answer: Following are the various notable differences between Angular and
Backbone.js
Architecture
Backbone.js makes use of the MVP architecture and doesn’t offer any data binding
process. Angular, on the contrary, works on the MVC architecture and makes use of
two-way data binding for driving application activity.
Community Support
Being backed by Google greatly ups the community support received by the Angular
framework. Also, extensive documentation is available. Although Backbone.js has a
good level of community support, it only documents on Underscore.js templates, not
much else.
Data Binding
Angular uses two-way data binding process and thus is a bit complex. Backbone.js,
on the contrary, doesn’t have any data binding process and thus, has a simplistic
API.
DOM
The prime focus of Angular JS is upon valid HTML and dynamic elements that
imitate the underlying data for rebuilding the DOM as per the specified rules and
then works on the updated data records.
Backbone.js follows the direct DOM manipulation approach for representing data
and application architecture changes.
Performance
Thanks to its two-way data binding functionality, Angular offers an impactful
performance for both small and large projects.
Backbone.js has a significant upper hand in performance over Angular in small data
sets or small webpages. However, it is not recommended for larger webpages or
large data sets due to the absence of any data binding process.
Templating
Angular supports templating via dynamic HTML attributes. These are added to the
document to develop an easy to understand application at a functional level. Unlike
Angular, Backbone.js uses Underscore.js templates that aren’t fully-featured as
Angular templates.
The Approach to Testing
The approach to testing varies greatly between Angular and Backbone.js due to the
fact that while the former is preferred for building large applications the latter is ideal
for developing smaller webpages or applications.
For Angular, unit testing is preferred and the testing process is smoother through the
framework. In the case of Backbone.js, the absence of a data binding process allows
for a swift testing experience for a single page and small applications.
Type
Angular is an open-source JS-based front-end web application framework that
extends HTML with new attributes. On the other hand, Backbone.js is a lightweight
JavaScript library featuring a RESTful JSON interface and MVP framework.
Question: How do Observables differ from Promises?
Answer: As soon as a promise is made, the execution takes place. However, this is
not the case with observables because they are lazy. This means that nothing
happens until a subscription is made. While promises handle a single event,
observable is a stream that allows passing of more than one event. A callback is
made for each event in an observable.
Question: Please explain the difference between Angular and AngularJS?
Answer: Various differences between Angular and AngularJS are stated as follows:
Architecture - AngularJS supports the MVC design model. Angular relies on
components and directives instead
Dependency Injection (DI) - Angular supports a hierarchical Dependency Injection
with unidirectional tree-based change detection. AngularJS doesn’t support DI
Expression Syntax - In AngularJS, a specific ng directive is required for the image or
property and an event. Angular, on the other hand, use () and [] for blinding an event
and accomplishing property binding, respectively
Mobile Support - AngularJS doesn’t have mobile support while Angular does have
Recommended Language - While JavaScript is the recommended language for
AngularJS, TypeScript is the recommended language for Angular
Routing - For routing, AngularJS uses $routeprovider.when() whereas Angular uses
@RouteConfig{(…)}
Speed - The development effort and time are reduced significantly thanks to support
for two-way data binding in AngularJS. Nonetheless, Angular is faster thanks to
upgraded features
Structure - With a simplified structure, Angular makes the development and
maintenance of large applications easier. Comparatively, AngularJS has a less
manageable structure
Support - No official support or updates are available for the AngularJS. On the
contrary, Angular has active support with updates rolling out every now and then
Question: Observe the following image:
What should replace the “?”?
Answer: Directives. The image represents the types of directives in Angular;
Attribute, structural, and custom.
Question: Could you explain the concept of templates in Angular?
Answer: Written with HTML, templates in Angular contains Angular-specific attributes
and elements. Combined with information coming from the controller and model,
templates are then further rendered to cater the user with the dynamic view.
Question: Explain the difference between an Annotation and a Decorator in
Angular?
Answer: In Angular, annotations are used for creating an annotation array. They are
only metadata set of the class using the Reflect Metadata library.
Decorators in Angular are design patterns used for separating decoration or
modification of some class without changing the original source code.
Question: What are directives in Angular?
Answer: Directives are one of the core features of Angular. They allow an Angular
developer to write new, application-specific HTML syntax. In actual, directives are
functions that are executed by the Angular compiler when the same finds them in the
DOM. Directives are of three types:
Attribute Directives
Component Directives
Structural Directives
Question: What are the building blocks of Angular?
Answer: There are essentially 9 building blocks of an Angular application. These are:
Components – A component controls one or more views. Each view is some specific
section of the screen. Every Angular application has at least one component, known
as the root component. It is bootstrapped inside the main module, known as the root
module. A component contains application logic defined inside a class. This class is
responsible for interacting with the view via an API of properties and methods.
Data Binding – The mechanism by which parts of a template coordinates with parts
of a component is known as data binding. In order to let Angular know how to
connect both sides (template and its component), the binding markup is added to the
template HTML.
Dependency Injection (DI) – Angular makes use of DI to provide required
dependencies to new components. Typically, dependencies required by a
component are services. A component’s constructor parameters tell Angular about
the services that a component requires. So, a dependency injection offers a way to
supply fully-formed dependencies required by a new instance of a class.
Directives – The templates used by Angular are dynamic in nature. Directives are
responsible for instructing Angular about how to transform the DOM when rendering
a template. Actually, components are directives with a template. Other types of
directives are attribute and structural directives.
Metadata – In order to let Angular know how to process a class, metadata is
attached to the class. For doing so decorators are used.
Modules – Also known as NgModules, a module is an organized block of code with a
specific set of capabilities. It has a specific application domain or a workflow. Like
components, any Angular application has at least one module. This is known as the
root module. Typically, an Angular application has several modules.
Routing – An Angular router is responsible for interpreting a browser URL as an
instruction to navigate to a client-generated view. The router is bound to links on a
page to tell Angular to navigate the application view when a user clicks on it.
Services – A very broad category, a service can be anything ranging from a value
and function to a feature that is required by an Angular app. Technically, a service is
a class with a well-defined purpose.
Template – Each component’s view is associated with its companion template. A
template in Angular is a form of HTML tags that lets Angular know that how it is
meant to render the component.
Question: Please explain the differences between Angular and jQuery?
Answer: The single biggest difference between Angular and jQuery is that while the
former is a JS frontend framework, the latter is a JS library. Despite this, there are
some similarities between the two, such as both features DOM manipulation and
provides support for animation.
Nonetheless, notable differences between Angular and jQuery are:
Angular has two-way data binding, jQuery does not
Angular provides support for RESTful API while jQuery doesn’t
jQuery doesn’t offer deep linking routing though Angular supports it
There is no form validation in jQuery whereas it is present in Angular
Question: Could you explain the difference between Angular expressions
and JavaScript expressions?
Answer: Although both Angular expressions and JavaScript expressions can contain
literals, operators, and variables, there are some notable dissimilarities between the
two. Important differences between Angular expressions and JavaScript expressions
are enlisted below:
Angular expressions support filters while JavaScript expressions do not
It is possible to write Angular expressions inside the HTML tags. JavaScript
expressions, contrarily, can’t be written inside the HTML tags
While JavaScript expressions support conditionals, exceptions, and loops, Angular
expressions don’t
Question: Can you give us an overview of Angular architecture?
Answer: You can draw some like this:
Here is Angular Architecture in detail: https://angular.io/guide/architecture
Question: What is Angular Material?
Answer: It is a UI component library. Angular Material helps in creating attractive,
consistent, and fully functional web pages as well as web applications. It does so
while following modern web design principles, including browser portability and
graceful degradation.
Question: What is AOT (Ahead-Of-Time) Compilation?
Answer: Each Angular app gets compiled internally. The Angular compiler takes in
the JS code, compiles it and then produces some JS code. This happens only once
per occasion per user. It is known as AOT (Ahead-Of-Time) compilation.
Question: What is Data Binding? How many ways it can be done?
Answer: In order to connect application data with the DOM (Data Object Model), data
binding is used. It happens between the template (HTML) and component
(TypeScript). There are 3 ways to achieve data binding:
Event Binding – Enables the application to respond to user input in the target
environment
Property Binding – Enables interpolation of values computed from application data
into the HTML
Two-way Binding – Changes made in the application state gets automatically
reflected in the view and vice-versa. The ngModel directive is used for achieving this
type of data binding.
Question: What is demonstrated by the arrow in the following image?
Answer: This represents a dependency injection or DI.
Question: Can you draw a comparison between the service() and the
factory() functions?
Answer: Used for the business layer of the application, the service() function
operates as a constructor function. The function is invoked at runtime using the new
keyword.
Although the factory() function works in pretty much the same way as the service()
function does, the former is more flexible and powerful. In actual, the factory()
function are design patterns that help in creating objects.
Question: Please explain the digest cycle in Angular?
Answer: The process of monitoring the watchlist in order to track changes in the
value of the watch variable is termed the digest cycle in Angular. The previous and
present versions of the scope model values are compared in each digest cycle.
Although the digest cycle process gets triggered implicitly, it is possible to start it
manually by using the $apply() function.
Question: Could you explain the various types of filters in AngularJS.
Answer: In order to format the value of expression so that it can be displayed to the
user, AngularJS has filters. It is possible to add these filters to the controllers,
directives, services, or templates. AngularJS also provides support for creating
custom filters.
Organizing data in such a way so that it is displayed only when certain criteria are
fulfilled is made possible using filters. Filters are added to the expressions using the
pipe ‘|’ character. Various types of AngularJS filters are enumerated as follows:
currency – Formats a number to the currency format
date – Formats a data to some specific format
filter – Selects a subset of items from an array
json – Formats an object to a JSON string
limitTo – Limits an array or string into a specified number of characters or elements
lowercase – Formats a string to lowercase
number – Formats a number to a string
orderBy – Orders an array by an expression
Question: What is new in Angular 6?
Answer: Here are some of the new aspects introduced in Angular 6:
Angular Elements – It allows converting Angular components into web components
and embeds the same in some non-Angular application
Tree Shakeable Provider – Angular 6 introduces a new way of registering a provider
directly inside the @Injectable() decorator. It is achieved by using the providedIn
attribute
RxJS 6 – Angular 6 makes use of RxJS 6 internally
i18n (internationalization) – Without having to build the application once per locale,
any Angular application can have “runtime i18n”
Question: What is ngOnInit()? How to define it?
Answer: ngOnInit() is a lifecycle hook that is called after Angular has finished
initializing all data-bound properties of a directive. It is defined as:
Interface OnInit {
ngOnInit() : void
}
Question: What is SPA (Single Page Application) in Angular? Contrast SPA
technology with traditional web technology?
Answer: In the SPA technology, only a single page, which is index.HTML, is
maintained although the URL keeps on changing. Unlike traditional web technology,
SPA technology is faster and easy to develop as well.
In conventional web technology, as soon as a client requests a webpage, the server
sends the resource. However, when again the client requests for another page, the
server responds again with sending the requested resource. The problem with this
technology is that it requires a lot of time.
Question: What is the code for creating a decorator?
Answer: We create a decorator called Dummy:
function Dummy(target) {
dummy.log('This decorator is Dummy', target);
}
Question: What is the process called by which TypeScript code is
converted into JavaScript code?
Answer: It is called Transpiling. Even though TypeScript is used for writing code in
Angular applications, it gets internally transpiled into equivalent JavaScript.
Question: What is ViewEncapsulation and how many ways are there do to
do it in Angular?
Answer: To put simply, ViewEncapsulation determines whether the styles defined in
a particular component will affect the entire application or not. Angular supports 3
types of ViewEncapsulation:
Emulated – Styles used in other HTML spread to the component
Native – Styles used in other HTML doesn’t spread to the component
None – Styles defined in a component are visible to all components of the
application
Question: Why prioritize TypeScript over JavaScript in Angular?
Answer: TypeScript is a superset of Javascript as it is Javascript + Types or extra
features like typecasting for variables, annotations, variable scope and much more.
The typescript is designed in a way to overcome Javascript shortcomings like
typecasting of variables, classes, decorators, variable scope and many more.
Moreover, Typescript is purely object-oriented programming that offers a "Compiler"
that can convert to Javascript-equivalent code.
Question: Discuss the lifecycle designed for directive and components in
Angular JS especially for the newly introduced version 6.0?
Answer:
Components and directive of Angular JS follow the following typical lifecycle.
nhOnInit
ngDoCheck
ngOnDestroy
Constructor
ngOnChanges
ngAfterContentInit (only for components)
ngAfterContentChecked (only for components)
ngAfterViewInit (only for components)
ngAfterViewChecked (only for components)
Question: Write the features for Angular 6 over Angular 5.
Answer: Following are the features:
1. Added ng update
CLI command updates angular project dependencies to their latest versions. The ng
update is a normal package manager tool to identify and update in normal package
manager tools to identify and update other dependencies.
2. Uses RxJS6
This is the third party library (RxJS) and introduces two important changes as
compared to RxJS5.
Introduces a new internal package structure.
Operator concept
To update of RxJS6, run the following command:
npm install --save rxjs@6
To update your existing Angular Project, run the following:
npm install --save rxjs-compat
3. The <ng-template>
Angular 6 uses <ng-template> instead of <template>
4. Service Level Changes
If in an earlier version, the user wanted to provide a service to the entire application,
the user was required to add it to providers in the AppModule but it is not required in
the case of Angular6.
5. Renamed Operators
Angular 6 has renamed following operators:
do() => tap()
catch() => catchError()
finally() => finalize()
switch()=>switchAll()
throw() => throwError
Question: State some advantages of Angular over other frameworks.
Answer:
Out of box Features: Several built-in features like routing, state management, rxjs
library, and HTTP services are straight out of the box services provided by Angular.
So, one does not need to look for the above-stated features separately.
Declarative UI: Angular uses HTML to render the UI of an application as it is a
declarative language and is much easier to use than JavaScript.
Long-term Google Support: Google plans to stick with Angular and further scale up
its ecosystem as it has offered its long term support to Angular.
Question: What is the difference between Angular and AngularJS.
Answer:
Parameters AngularJS Angular
MVC or Model-View-Controller
architecture facilitates the AngularJS
framework, where the Model contains Angular replaces controllers with
Architecture the business logic and Controllers Components that are directives
processes information, lastly, View with a predefined template.
shows the information present in the
Model.
Angular uses TypeScript
language, a statically typed
AngularJS uses JavaScript language, language, and a superset of
Language
which is a dynamically typed language. JavaScript. Angular provides
better performance while
developing larger applications.
Supported by all popular mobile
Mobile Support Does not support mobile support.
browsers.
The process of maintaining code It is easier to maintain code for
Structure becomes tedious in the case of larger larger applications as it provides
applications. a better structure.
A developer needs to remember the Property binding is done using
Expression Syntax correct ng-directive for binding an event "[ ]" attribute and event binding is
or a property. done using "( )" attribute.
Angular uses
Routing AngularJS uses $routeprovider.when()
@RouteConfig{(…)}
The development effort and time are
Angular is faster due to
Speed reduced significantly because of the
upgraded features.
two-way data binding
Angular supports a hierarchical
Dependency Injectio Dependency Injection with
AngularJS doesn’t support DI.
n unidirectional tree-based change
detection.
Angular has active support with
No official support or updates are
Support updates rolling out every now
available for AngularJS.
and then.
How do we call multiple parallel API calls at the same time in angular ?
ANS) RXJS ForkJoin operator
Pipes :
(1) Percent
(2) Async
(3) Number
(4) Currency
(5) Date
(6) Lowercase
(7) Uppercase
(8) Titlecase
(9) Slice
(10) Json
Angular v11 Angular v12
Typescript 4.0 Typescript 4.2
Webpack 5 Support Webpack 5.37 Support
strict checks with a flag. Default strict mode
Deprecation of IE 9, 10, and IE
Deprecating support for IE11.
mobile.
Updates on Operation Byelog. Improved component tests harness.
Updated Language Service
Http improvements.
Preview.
Migration to ESLint Migrating from legacy i18n message IDs
Roadmap to inform about the priorities of the Angular
Roadmap to provide early feedback
team
Updated Language Service Preview Migration to default IVY-based language service
New Default Browser Configuration Updated Language Service Preview
Improved Ngcc compiler Improved logging and reporting
Angular 11 release date : Nov 11, 2020
Angular 12 release date : May 12, 2021
Angular 13 release date : Nov 03, 2021
How to use data from observable without subscribing in angular ?
A) Using async pipe
B) {{ objObservable | async }}
Why Do You Need a Framework?
Frameworks in general boost web development efficiency and
performance by providing a consistent structure so that developers don’t
have to keep rebuilding code from scratch. Frameworks are time savers
that offer developers a host of extra features that can be added to
software without requiring extra effort.
Why Angular?
JavaScript is the most commonly used client-side scripting language. It is
written into HTML documents to enable interactions with web pages in
many unique ways. As a relatively easy-to-learn language with pervasive
support, it is well-suited to develop modern applications.
But is JavaScript ideal for developing single-page applications that require
modularity, testability, and developer productivity? Perhaps not.
These days, we have a variety of frameworks and libraries designed to
provide alternative solutions. With respect to front-end web development,
Angular addresses many, if not all, of the issues developers face when
using JavaScript on its own.
Angular Architecture
Angular is a full-fledged model-view-controller (MVC) framework. It
provides clear guidance on how the application should be structured and
offers bi-directional data flow while providing real DOM.
The following are the eight building blocks of an Angular application:
1. Modules
A module is a feature area in an angular application . An Angular app has
a root module, named AppModule, which provides the bootstrap
mechanism to launch the application.
2. Components
Components are the building blocks of angular application.
Each component in the application defines a class that holds the
application logic and data. A component generally defines a part of the
user interface (UI).
3. Templates
The Angular template combines the Angular markup with HTML to modify
HTML elements before they are displayed. There are two types of data
binding:
1. Event binding: Lets your app respond to user input in the target
environment by updating your application data.
2. Property binding: Enables users to interpolate values that are computed
from your application data into the HTML.
4. Metadata
Metadata tells Angular how to process a class. It is used to decorate the
class so that it can configure the expected behavior of a class.
5. Services
When you have data or logic that isn’t associated with the view but has to
be shared across components, a service class is created. The class is
always associated with the @Injectable decorator.
6. Dependency Injection
This feature lets you keep your component classes crisp and efficient. It
does not fetch data from a server, validate the user input, or log directly
to the console. Instead, it delegates such tasks to the services.
Angular comes with its own set of advantages and disadvantages. The
next two sections briefly explain them.
Async Pipe
The async pipe in angular will subscribe to an Observable or Promise and
return the latest value it has emitted. Whenever a new value is emitted
from an Observable or Promise, the async pipe marks the component to
be checked for changes. When the component gets destroyed, the async
pipe unsubscribes automatically to avoid potential memory leaks. We can
use the async pipe in Angular application by including the CommonModule
which exports all the basic Angular directives and pipes, such as NgIf,
NgForOf, DecimalPipe, and so on. These are then re-exported by
BrowserModule, which is included automatically in the root AppModule,
when you create a new app with the CLI new command.
Syntax of AsyncPipe
The below syntax shows how we can use the async pipe with the object
expression.
{{obj_expression | async}}
Using AsyncPipe with Promises
Async pipe for promises automatically adds a then callback and renders
the response. Now let’s see an example where we are binding a Promise to
the view. Clicking the Resolve button resolves the promise.
1@Component({
2 selector: 'async -pipe',
3 template: `<div>
4 <code>promise|async</code>:
5 <button (click)="clicked()">{{ arrived ? 'Reset' :
'Resolve' }}</button>
6 <span>Wait for it... {{ logMessage | async
}}</span>
7 </div>`
8})
9export class AsyncPipeComponent {
10 logMessage: Promise<string>|null = null;
11 arrived: boolean = false;
12
13 private resolve: Function|null = null;
14
15 constructor() { this.reset(); }
16
17 reset() {
18 this.arrived = false;
19 this.logMessage = new Promise<string>((resolve,
reject) => { this.resolve = resolve; });
20 }
21
22 clicked() {
23 if (this.arrived) {
24 this.reset();
25 } else {
26 this.resolve !('hi there!');
27 this.arrived = true;
28 }
29 }
30}
typescript
In the above example, we pipe the output of our promise to the async pipe.
The property promise is the actual unresolved promise that gets returned
from logMessage without then being called on it.
Using AsyncPipe with Observables
AsyncPipes for Observables automatically subscribes to the observable,
renders the output, and then also unsubscribes when the component is
destroyed. So, we don’t need to handle the cleanup logic ourselves. There
is no need to unsubscribe manually in the component. Angular handles
subscriptions of async pipes for us automatically using ngOnDestroy.
AsyncPipe uses the OnPush change detection out of the box. We need to
make sure that all our business logic is immutable and always returns new
objects. We can say that the OnPush change detection strategy is great for
performance so we should be using an async pipe as much as possible.
Moreover, we could argue that the consistent use of these features
simplifies application because developers can always assume one-way
data flow and automatic subscription management. We can also use an
async pipe with Observables. Now let’s see the example below that binds
the time Observable to the view. The Observable continuously updates the
view with the current time.
1@Component({
2 selector: 'async -pipe-observable',
3 template: '<div><code>observable|async</code>: Time:
{{ time | async }}</div>'
4})
5export class AsyncPipeObservableComponent {
6 time = new Observable<string>((observer:
Observer<string>) => {
7 setInterval(() => observer.next(new
Date().toString()), 1000);
8 });
9}
typescript
In the above example, when we pipe our observable directly to the async
pipe, the async pipe performs a subscription for us and then returns
whatever gets passed to it. Advantages of using the async pipe are: 1. We
don’t need to call subscribe on our observable and store the intermediate
data on our component. 2. We don’t need to remember to unsubscribe from
the observable when the component is destroyed.
Advantages of Using AsyncPipe over
Subscribe
1AsyncPipe uses the OnPush change detection out of
the box. We need to make sure that all our business
logic is immutable and always returns new objects.
Using subscribe() introduces a complementary need to unsubscribe
at the end of the component life-cycle to avoid memory leaks.
Developers have to unsubscribe manually. The most RxJS
(declarative) common way to do this is to using
takeUntil(unsubscribe$).
There is no need to unsubscribe manually in the component. Angular
handles subscriptions of async pipes for us automatically using
ngOnDestroy.
Using subscribe unwraps property to be used in multiple places in the
template “as it is” without the need to rely on various workarounds.
The Unwrapped property is available everywhere in the component.
This means it can be used directly in the component’s method
without the need to pass it from the template. That way, all of the
states can be kept in the component.
The OnPush change detection strategy is great for performance, so
we should be using async pipe as much as possible. More so, we
could argue that the consistent use of these features simplifies
applications because developers can always assume one-way data
flow and automatic subscription management.
Let’s consider an example below where we are using the async pipe in the
EmployeesComponent class without using the subscribe. And there is no
need to use the unwrapped property to use in the component and the
template.
1@Component({
2 template: `
3 <ul *ngIf="(employees$ | async).length">
4 <li *ngFor="let employee of employees$ |
async">{{employee.name}}</li>
5 </ul>
6 `
7})
8export class EmployeesComponent implements OnInit {
9 employees$: Observable<Employee[]>;
10
11 constructor(private dept: Department<State>) {}
12
13 ngOnInit() {
14 this. employees$ =
this.dept.pipe(select(selectEmployees))
15 }
16}
Q1: What is Routing Guard in Angular?
Answer
Angular’s route guards are interfaces which can tell the router whether or not it should allow
navigation to a requested route. They make this decision by looking for a true or false return
value from a class which implements the given guard interface.
There are five different types of guards and each of them is called in a particular sequence. The
router’s behavior is modified differently depending on which guard is used. The guards are:
CanActivate
CanActivateChild
CanDeactivate
CanLoad
Resolve – Before loading component we want data from DB,we can use this
guard
Consider:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
Q13: How would you protect a component being activated through the router?
Answer
The Angular router ships with a feature called guards. These provide us with ways to control the
flow of our application. We can stop a user from visiting certain routes, stop a user from leaving
routes, and more. The overall process for protecting Angular routes:
Create a guard service: ng g guard auth
Create canActivate() or canActivateChild() methods
Use the guard when defining routes
// import the newly created AuthGuard
const routes: Routes = [
{
path: 'account',
canActivate: [AuthGuard]
}
];
Some other available guards:
CanActivate: Check if a user has access
CanActivateChild: Check if a user has access to any of the child routes
CanDeactivate: Can a user leave a page? For example, they haven't finished editing a
post
Resolve: Grab data before the route is instantiated
CanLoad: Check to see if we can load the routes assets
What is an Auth guard?
AuthGuard is a class which implements the interface CanActivate , to decide
whether the user has access/permission to view specific page / route / path in
the application or not. This will be useful when we need
authentication/authorization based control over the application
What are Subjects ?
A Subject is a special type of Observable that allows values to be
multicasted to many Observers. The subjects are also observers
because they can subscribe to another observable and get value
from it, which it will multicast to all of its subscribers.
Basically, a subject can act as both observable & an observer.
Subject Vs BehaviorSubject
Now you know how both Subject and BehaviorSubject works. The main problem
you get is that when can we use Subject and when can we use BehaviorSubject.
By knowing the difference between them you can get idea when to use which
observable.
Values they hold
If you subscribe to a Subject, we won’t get current value or initial value.
But when you subscribe to a BehaviorSubject, you will get the current or initial
value.
Initial Value
For Subject, we don't need to initial a value.
But whenever we declare BehaviorSubject we need to initialize a default value.
Subscribers
In Subject, the subscribers will only receive the upcoming value.
In BehaviorSubject, the subscribers will receive the previous value and also
upcoming value.
TypeScript Vs. JavaScript
SN JavaScript TypeScript
1. It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature.
2. Netscape developed it in 1995. Anders Hejlsberg developed it in 2012.
3. JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.
4. It is directly run on the browser. It is not directly run on the browser.
5. It is just a scripting language. It supports object-oriented programming concep
interfaces, inheritance, generics, etc.
6. It doesn't support optional parameters. It supports optional parameters.
7. It is interpreted language that's why it It compiles the code and highlighted errors
highlighted the errors at runtime. development time.
8. JavaScript doesn't support modules. TypeScript gives support for modules.
9. In this, number, string are the objects. In this, number, string are the interface.
10. JavaScript doesn't support generics. TypeScript supports generics.
11. Example: Example:
<script> function addNumbers(a, b) {
function addNumbers(a, b) { return a + b;
return a + b; }
} var sum = addNumbers(15, 25);
var sum = addNumbers(15, 25); console.log('Sum of the numbers is: ' + sum);
document.write('Sum of the numbers is: ' +
sum);
</script>
What Are Interceptors?
Interceptor is a special Angular Service that can be used to
intercept all the request and response calls and modify
them to our requirement.
Interceptors allow us to intercept incoming or
outgoing HTTP requests using the HttpClient. They can
handle both HttpRequest as well as HttpResponse.
By intercepting the Http request, we can modify or change
the value of the request, and by intercepting the response,
we can do some predefined actions on a particular status
code or message.
Most interceptors transform the outgoing request before
passing it to the next interceptor in the chain(if there are
multiple interceptors), by calling the
next.handle(transformedReq).
We can transform the response stream by applying
additional RxJS operators on the stream returned by the
next.handle().
Closures & Angular
During the interview, most of the people are able to answer when asked
about Closures and their general examples. But when asked about the
same if they have used or seen it anywhere in their angular application
most of them failed to provide an example. So I thought to document a
basic example of closure in Angular.
Closures
A closure is the combination of a function bundled together (enclosed)
with references to its surrounding state (the lexical environment). In other
words, a closure gives you access to an outer function’s scope
from an inner function. In JavaScript, closures are created every
time a function is created, at function creation time.
Now breaking up the definition for better understanding.
A closure gives you access to an outer function’s scope from an inner
function.
So basically after execution of the outer function, the inner function can
remember the scope (e.g. if there are any variables in the outer function
the inner function can access them).
So, in Angular, we usually subscribe to any API call inside the ngOnInit
function. Something like the below example.
ngOnInit() {
this.api.get('users?page=1').subscribe(res => {
this.users = res;
console.log('data response', this.users);
}, error => {
console.log(error);
});
}
Here the subscribe and error functions are acting as inner functions and
the ngOnInit is acting as an outer function. And we can access any
variables or methods of the component using this keyword. This means it
remembers the scope of the outer function.
What is Module ?
A module is a feature area in your angular application
How browser finds a website ? How the web works ?
How the web works provides a simplified view of what happens when you
view a webpage in a web browser on your computer or phone.
This theory is not essential to writing web code in the short term, but
before long you'll really start to benefit from understanding what's
happening in the background.
Clients and servers
Computers connected to the web are called clients and servers. A simplified diagram of how
they interact might look like this:
Clients are the typical web user's internet-connected devices (for example, your computer
connected to your Wi-Fi, or your phone connected to your mobile network) and web-
accessing software available on those devices (usually a web browser like Firefox or
Chrome).
Servers are computers that store webpages, sites, or apps. When a client device wants to
access a webpage, a copy of the webpage is downloaded from the server onto the client
machine to be displayed in the user's web browser.
The other parts of the toolbox
The client and server we've described above don't tell the whole story. There are many other
parts involved, and we'll describe them below.
For now, let's imagine that the web is a road. On one end of the road is the client, which is
like your house. On the other end of the road is the server, which is a shop you want to buy
something from.
In addition to the client and the server, we also need to say hello to:
Your internet connection: Allows you to send and receive data on the web. It's basically like
the street between your house and the shop.
TCP/IP: Transmission Control Protocol and Internet Protocol are communication protocols
that define how data should travel across the internet. This is like the transport mechanisms
that let you place an order, go to the shop, and buy your goods. In our example, this is like a
car or a bike (or however else you might get around).
DNS: Domain Name System is like an address book for websites. When you type a web
address in your browser, the browser looks at the DNS to find the website's IP address
before it can retrieve the website. The browser needs to find out which server the website
lives on, so it can send HTTP messages to the right place (see below). This is like looking up
the address of the shop so you can access it.
HTTP: Hypertext Transfer Protocol is an application protocol that defines a language for
clients and servers to speak to each other. This is like the language you use to order your
goods.
Component files: A website is made up of many different files, which are like the different
parts of the goods you buy from the shop. These files come in two main types:
o Code files: Websites are built primarily from HTML, CSS, and JavaScript, though
you'll meet other technologies a bit later.
o Assets: This is a collective name for all the other stuff that makes up a website, such
as images, music, video, Word documents, and PDFs.
So what happens, exactly?
When you type a web address into your browser (for our analogy that's like walking to the
shop):
1. The browser goes to the DNS server, and finds the real address of the server that the
website lives on (you find the address of the shop).
2. The browser sends an HTTP request message to the server, asking it to send a copy of the
website to the client (you go to the shop and order your goods). This message, and all other
data sent between the client and the server, is sent across your internet connection using
TCP/IP.
3. If the server approves the client's request, the server sends the client a "200 OK" message,
which means "Of course you can look at that website! Here it is", and then starts sending the
website's files to the browser as a series of small chunks called data packets (the shop gives
you your goods, and you bring them back to your house).
4. The browser assembles the small chunks into a complete web page and displays it to you
(the goods arrive at your door — new shiny stuff, awesome!).
Order in which component files are parsed
When browsers send requests to servers for HTML files, those HTML files often
contain <link> elements referencing external CSS stylesheets and <script> elements
referencing external JavaScript scripts. It's important to know the order in which those files
are parsed by the browser as the browser loads the page:
The browser parses the HTML file first, and that leads to the browser recognizing
any <link>-element references to external CSS stylesheets and any <script>-element
references to scripts.
As the browser parses the HTML, it sends requests back to the server for any CSS files it has
found from <link> elements, and any JavaScript files it has found
from <script> elements, and from those, then parses the CSS and JavaScript.
The browser generates an in-memory DOM tree from the parsed HTML, generates an in-
memory CSSOM structure from the parsed CSS, and compiles and executes the parsed
JavaScript.
As the browser builds the DOM tree and applies the styles from the CSSOM tree and
executes the JavaScript, a visual representation of the page is painted to the screen, and the
user sees the page content and can begin to interact with it.
DNS explained
Real web addresses aren't the nice, memorable strings you type into your address bar to find
your favorite websites. They are special numbers that look like this: 63.245.215.20.
This is called an IP address, and it represents a unique location on the web. However, it's not
very easy to remember, is it? That's why Domain Name Servers were invented. These are
special servers that match up a web address you type into your browser (like "mozilla.org") to
the website's real (IP) address.
Websites can be reached directly via their IP addresses. You can use a DNS lookup tool to
find the IP address of a website.
Packets explained
Earlier we used the term "packets" to describe the format in which the data is sent from server
to client. What do we mean here? Basically, when data is sent across the web, it is sent in
thousands of small chunks. There are multiple reasons why data is sent in small packets.
They are sometimes dropped or corrupted, and it's easier to replace small chunks when this
happens. Additionally, the packets can be routed along different paths, making the exchange
faster and allowing many different users to download the same website at the same time. If
each website was sent as a single big chunk, only one user could download it at a time, which
obviously would make the web very inefficient and not much fun to use.
Optimize Angular bundle size in 4 steps
Have a long initial page loading time? check this out.
Photo by Aron Visuals on Unsplash
AngularInDepth is moving away from
Medium. This article, its updates and more recent
articles are hosted on the new
platform inDepth.dev
Have your web app ever been complained about taking too
long to load? Have you ever been given a task to “optimize
performance” of the slow app? There are tons of topics
about improving your app’s performance, such as lazy
loading, change detection, server side rendering, etc. One
of the topic I want to talk about here, is optimizing Angular
bundle size. It’s extremely easy and useful.
Step 1: Know your Bundle Size
It’s hard to deny that initial page loading time is tightly
connected with your Angular app bundle size.
By running ng build --prod you will see the bundles size of the
files the browser would get from your server.
What size is considered good or bad?
Usually among those 4 files in the image above,
only main.*.js is likely to go big or crazy. I checked
many apps built with Angular and have a feeling that most
medium size enterprise apps should have main.*.js under
500 KB, on average 250KB. If your bundle size largely
exceed those numbers, you may need to be aware. If your
bundle size is under this number, you may still want to
optimize it further.
Step 2: Are your files gzipped?
Generally speaking, gzipped file has only about 20% the
size of the original file, which can drastically decrease the
initial load time of your app.
To check if you have gzipped your files, just open the
network tab of developer console. In the “Response
Headers”, if you should see “Content-Encoding: gzip”, you
are good to go.
If you don’t see this header, your browser will load the
original files. For example, for the Angular bundle in the
image below, the browser will
load main.0d17aff85f337483317e.js and cost 2.21MB data.
However, if you gzip your file, your browser could only
load 495.13KB. Such a huge reduction of file size, will
obviously reduce the initial page loading time, especially
when user has low internet speed.
How to gzip?
If you host your Angular app in most of the cloud platforms
or CDN, you should not worry about this issue as they
probably have handled this for you. However, if you have
your own server (such as NodeJS + expressJS) serving
your Angular app, definitely check if the files are gzipped.
The following is an example to gzip your static assets in a
NodeJS + expressJS app. You can hardly imagine this dead
simple middleware “compression” would reduce your
bundle size from 2.21MB to 495.13KB.
const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())
Gzip is not the only way to compress, Brotli is also an
option.
Step 3: Analyze your Angular bundle
If your bundle size does get too big you may want to
analyze your bundle because you may have used an
inappropriate large-sized third party package or you forgot
to remove some package if you are not using it anymore.
Webpack has an amazing feature to give us a visual idea of
the composition of a webpack bundle.
It’s super easy to get this graph.
1. npm install -g webpack-bundle-analyzer
2. In your Angular app, run ng build --stats-json (don’t use
flag --prod). By enabling --stats-json you will get an
additional file stats.json
3. Finally, run webpack-bundle-analyzer
and your browser will pop up the
path/to/your/stats.json
page at localhost:8888. Have fun with it.
You may be surprised,
a) that you forgot to remove some packages you are not
using anymore and/or
b) that some packages are way larger than expected and
could be replaced with another one and/or
c) that you have improperly imported some libraries (For
example, 80% of moment.js is just locale data which is
probably not needed) so that you have some direction to
look for an answer.
Step 4: Monitor your bundle size
In Angular 7 and later, when you generate a new app
with ng new, in angular.json, you can find a configuration like:
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
}
]
This will give you a warning if you build Angular and the
bundle size exceeds 2MB and throw an error if the bundle
size exceeds 5MB. You can adjust the numbers as per your
need.
You can leverage this feature in your CI/CD pipeline. If you
see the warning/error, you may want to investigate what’s
going wrong.
Other ways to reduce bundle size
If your bundle size does get too big because of your app is
as big as Facebook, you should really use lazy-loading.
This topic is widely covered by the Angular community, so
I won’t spread it out here.
Angular - How to improve bundle size. And make
your Angular app load faster.
Daniel Kreider - 08. May. 2021
Angular Performance
Angular Performance Tweaks
Angular Load Speed
Is your Angular application slow?
Here are 5 ways you can reduce the bundle size. And make it load
faster. ⚡️
Want to skip the read? Click here to go straight to the 5 ways.
Slow.
Angular.
Applications.
Angular developers commonly wrestle with performance issues.
It's one of the biggest draw-backs and troubles that frustrate Angular
developers.
They're frustrated with Angular apps that are as agile as a dying cow.
How do I know? 🙊
Recently I surveyed a handful of Angular developers and asked them what
their biggest frustration with Angular is. Here's what they told me.
And small wonder.
I grabbed the Angular CLI and generated a basic app. No fancy
components. No extra packages or dependencies. Not even Angular
routing.
And what do you think the size of the build files were?
Not to bad. I guess.
But I'd say that for a basic Angular web app with no kind of logical
purpose that's a bit big.
And if we aren't careful our Angular apps will get heavy, fast.
So what can you do to reduce your bundle size?
How do you make the bundle size of your Angular app smaller?
What do you do if the main.js of your Angular application is too large?
How do you optimize the bundle size of your Angular app?
And what can be done to make your Angular app load faster?
Here are 4 ways to improve the bundle size of your Angular app. And in
my experience, these 5 places are the best direction to aim your guns.
Investigate your app module. It has a sneaky way of growing on us.
Lazy-load modules. Put that Angular app on a good diet.
Tune your imports. Or you'll be singing a slower tune.
Automatically compress the build. Woooola GZIP and Webpack!
Update to the latest version of Angular. Is it actually this simple?
1. Investigate your app module. It has a sneaky way of
growing on us.
Recently I was working on a business application built with Angular. I
knew the project like the back of my hand. Or at least I thought I did,
because I was the main developer and had written 95% of the code for the
project.
Then I decided to do a round of optimization to make it run faster. After
some diagnosing I decided the main*.js files that bootstrap the Angular
application were rather large. There must be some unused imports in
our app.module.ts file just adding a bunch-a trash to my Angular
application.
When I opened the app.module.ts file I was shocked! 😲
It was busting with imports and libraries that the project had since
outgrown.
So what did I do? I yanked those imports out and trimmed the project up,
nice and clean, just like a hipster-house-puppy.
Yes buddy, if your Angular app bundle is too large the first place I'd go
hunting is in the app.module.ts.
You might scare up some weird stuff. 🙈
2. Lazy-load modules. Put that Angular app on a good diet.
In case you didn't know it, Angular has a really cool feature called the
Angular module.
But what is it?
Angular modules are chunks of code that can be imported into various
parts of your application. A module can contain grouped pieces of
components, services and other functionality, each focused on a feature
area, specific domain, workflow, etc...
And why are they cool?
They're cool because Angular modules brings the power of modules to
web applications. As far as I know there is no other frontend library or
framework that does this as well as Angular does.
As your Angular application develops and matures, you must split the
various parts of your web application into feature modules that can be
loaded later if you're going to improve the size of your build bundle.
And then these modules can be lazy-loaded later, after the main part of
your Angular application has been loaded and displayed to the user.
The Angular docs have a great article on how to set up lazy-loading. I'd
recommend you check it out.
And if you're not sure what kind of lazy-loading strategy to use, then I've
got you covered.
3. Tune your imports. Or you'll be singing a slow tune.
Some blooming idiot might call me a bag of oats for telling you to watch
your imports. They'll likely yell at me saying that the Angular tree-shaking
stuff is smart enough to weed out the unused or poor imports.
And though I wish they were true. And even though Angular tree-shaking
has improved. They're wrong. At least that's been my experience.
So... watch those imports and make sure that all unused imports are
snipped away.
Secondly, don't import an entire library and then only use part of it. When
you do an import make sure that you only import what you'll actually
need.
Instead of this...
import * as my-import from 'package-name';
...do this.
import { something } from 'package-name';
4. Automatically compress the build. Woooola GZIP and
Webpack!
The potential of this step is powerful.
So powerful that it could slash the bundle size of your Angular application
by up to 3 times.
In a nutshell, we'll customize the build process to zip our files using GZIP.
We'll do this by customizing the webpack build process.
The first step is to install the custom-webpack package. It's crucial that
you install the version that matches your Angular version so head over to
the package page and grab the installation instructions for your specific
version of Angular.
The second package you need to install is compression-webpack-plugin.
It's this simple.
npm install compression-webpack-plugin --save-dev
And now that we've got our dependencies installed we need to create
a webpack.config.json in the root directory of our Angular application. It'll
look like this.
var path = require('path');
var CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
entry: {
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash].js'
},
plugins: [
new CompressionPlugin()
]
};
And last but not least, we will have to change the angular.json file.
We'll configure Angular to use our custom webpack builder and webpack
config file.
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./webpack.config.js"
},
}
...
}
5. Update to the latest version of Angular. Is it actually this
simple?
Yup. It's this simple. Especially if you're running a really outdated version
of Angular like Angular 6 or Angular 7.
Angular performance continues to be improved so make sure you keep
your Angular application up to date.
Plus, it isn't hard. There are Angular apps with millions of users, and the
development teams are reporting that it only take 30 minutes or so to
update from one version of Angular to the next. Not to mention that the
Angular team has a really helpful upgrade website.
IVY
Ivy is much more efficient than ViewEngine. For each component in Angular less code is
generated since the compiler removes the unused parts of Angular. This has a huge impact
on the size of the app. The difference in bundle size between Angular 8 apps and Angular 9
apps is almost 40%.
As one of the foremost frontend development frameworks, each iteration
of Angular is eagerly awaited by developers all around the world. With a
host of new features, Angular 9 promises to be one of the biggest releases
made by Angular in the past 3 years.
We take a look at its biggest feature, the Ivy compiler, and some of the
new major features.
The Ivy Compiler
After being introduced in Angular 8 as an opt-in, the new Ivy compiler and
render pipeline is now the default compiler in Angular 9. Ivy promises
smaller bundle sizes, better debugging, and a boost in overall
performance. Even though Ivy doesn't affect your workflow in Angular, it
does have a major impact on the code being generated.
Let's take a look.
1. Smaller Apps
Image courtesy: Kara Erickson - What's New in Angular v9 ng-conf 2020 keynote.
You'll see a considerable boost in performance of
your apps.
Ivy is much more efficient than ViewEngine. For each component in
Angular less code is generated since the compiler removes the unused
parts of Angular. This has a huge impact on the size of the app. The
difference in bundle size between Angular 8 apps and Angular 9 apps is
almost 40%.
This is a big deal since one of the main drawbacks of Angular when
compared to other libraries like React and Vue is the app size. Also, the
drop in bundle sizes improves the overall performance of the apps you
build.
2. Faster and Efficient Testing
You'll see a positive impact on your development
timeline thanks to Ivy.
With Ivy, you can expect to see a 40-50% boost in test speeds of your
apps. This is mainly down to the implementation of TestBed, which has
been completely revamped and is now much more efficient.
Image courtesy: Kara Erickson - What's New in Angular v9 ng-conf 2020 keynote.
How did they do that?
Rather than recompiling all components during each test cycle,
the TestBed in Ivy avoids recompilation between tests unless a
component has been manually overridden.
3. More Debugging Tools
Image courtesy: Kara Erickson - What's New in Angular v9 ng-conf 2020 keynote.
Now you have more tools to debug your applications. You have the
new ng object for debugging while running an application in Dev Mode.
With this you can now gain access to instances of your components,
directives, etc.
4. Improved Handling of Styles and Style
Merging
Handling of styles has been greatly improved in Ivy. Usually what happens
is that if there were two competing definitions for a style, then those
styles would destructively replace each other. Now they are just merged
predictably.
Image courtesy: Kara Erickson - What's New in Angular v9 ng-conf 2020 keynote.
In Ivy, bindings do not depend on the timing of changes to these
expressions instead, there is a clear, consistent order of precedence with
the most specific style having the highest precedence. For example, a
binding to [style.color] overrides a conflicting binding to [style].
5. Lazy Loading
In Ivy, any component can be lazy loaded and dynamically rendered.
Components can be lazy loaded and rendered without Angular modules or
routing. Even the libraries which are only used by a lazy loaded
component are bundled into lazy-loaded chunks.
6. AOT Compilation
The AOT Compiler has seen a great deal of improvement because of Ivy's
new architecture. Till Angular 8, JIT compilation was preferred the
preferred compiler since AOT was too slow.
Now in Ivy AOT is the default compiler thanks to the huge improvements
in build and rebuild times.
1. Angular Ivy is the new default rendering engine.
2. Starting from version 9 of Angular, your TypeScript code will be
compiled using Ivy instead of the older ViewEngine (VE).
3. Basically, Ivy decreases your bundle sizes, enhances testing,
and improves debugging capabilities. In addition, Ivy uses
Ahead-of-Time compilation to speed up your apps.
To summarise -
+---------------------------+-------------------+
| Ivy | AOT |
+---------------------------+-------------------+
| It is a rendering engine. | It is a compiler. |
+---------------------------+-------------------+
Real difference would be between -
1. Ivy vs ViewEngine(VE)
2. AOT vs JIT
SOLID
Object oriented programming stands on 4 pillars : APIE
[Abstraction,Polymorphism,Inheritance,Encapsulation] . I order that we
confidently and professionally follow these pillars we need principles to guide
us. In 2002 he gave us principles that soon became to know as solid
SOLID is an acronym for the first five object-oriented design (OOD) principles by Robert C.
Martin (also known as Uncle Bob).
SOLID :
S = Single Responsibility Principle
There should never be more than one reason for a class to change.
O = Open Closed Principle
Software entities [classes, modules, functions] should be open for extension
but closed for modification.
L = Liskov Substitution Principle
Base classes should be able to use objects of derived class without them
knowing it.
I = Interface Segregation Principle
Clients should not be forced to depend on interfaces that they do not use.
D = Dependency Inversion Principle
High level modules should not depend on low level modules both should
depend on abstraction, abstraction should not depend on details, details both
should depend on abstraction.
7. What are lifecycle hooks in Angular? Explain a few lifecycle hooks.
Every component in Angular has a lifecycle, different phases it goes through from the time of
creation to the time it's destroyed. Angular provides hooks to tap into these phases and trigger
changes at specific phases in a lifecycle.
ngOnChanges( ) This hook/method is called before ngOnInit and whenever one or more input
properties of the component changes.
This method/hook receives a SimpleChanges object which contains the previous and current
values of the property. It is triggered when @input or @Output change
ngOnInit( ) This hook gets called once, after the ngOnChanges hook.
It initializes the component and sets the input properties of the component.
ngDoCheck( ) It gets called after ngOnChanges and ngOnInit and is used to detect and act on
changes that cannot be detected by Angular.
We can implement our change detection algorithm in this hook.
ngAfterContentInit( ) It gets called after the first ngDoCheck hook. This hook responds after the
content gets projected inside the component.
ngAfterContentChecked( ) It gets called after ngAfterContentInit and every
subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ) It responds after a component's view, or a child component's view is
initialized.
ngAfterViewChecked( ) It gets called after ngAfterViewInit, and it responds after the
component's view, or the child component's view is checked.
ngOnDestroy( ) It gets called just before Angular destroys the component. This hook can be used
to clean up the code and detach event handlers.
Let’s understand how to use ngOnInit hook, since it’s the most oftenly used hook. If one has to
process lot of data during component creation, it’s better to do it inside ngOnInit hook rather
than the constructor:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
this.processData();
}
processData(){
// Do something..
}
As you can see we have imported OnInit but we have used ngOnInit function. This principle
should be used with the rest of the hooks as well.
How to Create Custom
Validators in Angular
In this post, we look at how to create the functionality
that tells your user if they've entered in their
information correctly. In this blog post, we will learn how to
create custom validators in Angular Reactive Forms. If you are new
to reactive forms, learn how to create your first Angular reactive
form here.
Let's say we have a login form as shown in the code below. Currently, the
form controls do not have any validations attached to it.
1
ngOnInit() {
2
this.loginForm = new FormGroup({
3
email: new FormControl(null),
4
password: new FormControl(null),
5
age: new FormControl(null)
6
});
7
Here, we are using FormGroupto create a reactive form. On the
component template, you can attach loginForm as shown in the code
below. Using property binding, the formGroup property of the HTML
form element is set to loginForm and the formControlName value of
these controls is set to the individual FormControl property
of FormGroup.
This will give you a reactive form in your application:
Using Validators
Angular provides us many useful validators,
including required, minLength, maxLength, and pattern. These
validators are part of the Validators class, which comes with
the @angular/forms package.
Let's assume you want to add a required validation to the email control
and a maxLength validation to the password control. Here's how you do
that:
1
ngOnInit() {
2
this.loginForm = new FormGroup({
3
email: new FormControl(null, [Validators.required]),
4
password: new FormControl(null, [Validators.required,
Validators.maxLength(8)]),
5
age: new FormControl(null)
6
});
7
To work with validators, make sure to import them into the component
class:
1
import { FormGroup, FormControl, Validators } from '@angular/forms';
On the template, you can use validators to show or hide an error
message. Essentially, you are reading formControl using
the get() method and checking whether it has an error or not using
the hasError() method. You are also checking whether formControl is
touched or not using the touched property.
If the user does not enter an email, then the reactive form will show an
error as follows:
Custom Validators
Let us say you want the age range to be from 18 to 45. Angular does not
provide us range validation; therefore, we will have to write a custom
validator for this.
In Angular, creating a custom validator is as simple as creating another
function. The only thing you need to keep in mind is that it takes one
input parameter of type AbstractControl and it returns an object of
a key-value pair if the validation fails.
Let's create a custom validator called ageRangeValidator, where the
user should able to enter an age only if it's in a given range.
The type of the first parameter is AbstractControl, because it is a base
class of FormControl, FormArray, and FormGroup, and it allows you to
read the value of the control passed to the custom validator function.
The custom validator returns either of the following:
1. If the validation fails, it returns an object, which contains a key-
value pair. Key is the name of the error and the value is
always Booleantrue.
2. If the validation does not fail, it returns null.
Now, we can implement the ageRangeValidator custom validator in the
below listing:
1
function ageRangeValidator(control: AbstractControl): { [key: string]:
boolean } | null {
2
if (control.value !== undefined && (isNaN(control.value) ||
control.value < 18 || control.value > 45)) {
4
return { 'ageRange': true };
5
}
6
return null;
7
}
Here, we are hardcoding the maximum and minimum range in the
validator. In the next section, we will see how to pass these parameters.
Now, you can use ageRangeValidator with the age control as shown in
the code below. As you see, you need to add the name of the custom
validator function in the array:
1
ngOnInit() {
2
this.loginForm = new FormGroup({
3
email: new FormControl(null, [Validators.required]),
4
password: new FormControl(null, [Validators.required,
Validators.maxLength(8)]),
5
age: new FormControl(null, [ageRangeValidator])
6
});
7
On the template, the custom validator can be used like any other
validator. We are using the ageRange validation to show or hide the
error message.
If the user does not enter an age between 18 to 45, then the reactive
form will show an error:
Now the age control is working with the custom validator. The only
problem with ageRangeValidator is that the hardcoded age range only
validates numbers between 18 and 45. To avoid a fixed range, we need
to pass the maximum and minimum age to ageRangeValidator.
Passing Parameters to a Custom Validator
An Angular custom validator does not directly take extra input
parameters aside from the reference of the control. To pass extra
parameters, you need to add a custom validator inside a factory function.
The factory function will then return a custom validator.
You heard right: in JavaScript, a function can return another
function.
Essentially, to pass parameters to a custom validator you need to follow
these steps:
1. Create a factory function and pass parameters that will be passed
to the custom validator to this function.
2. The return type of the factory function should
be ValidatorFn which is part of @angular/forms
3. Return the custom validator from the factory function.
The factory function syntax will be as follows:
Now you can refactor the ageRangeValidator to accept input
parameters as shown in the listing below:
1
function ageRangeValidator(min: number, max: number): ValidatorFn {
2
return (control: AbstractControl): { [key: string]: boolean } | null =>
{
3
if (control.value !== undefined && (isNaN(control.value) ||
control.value < min || control.value > max)) {
4
return { 'ageRange': true };
5
}
6
return null;
7
};
8
We are using the input parameters max and min to validate age control.
Now, you can use ageRangeValidator with age control and pass the
values for max and min as shown in the code below:
1
min = 10;
2
max = 20;
3
ngOnInit() {
4
this.loginForm = new FormGroup({
5
email: new FormControl(null, [Validators.required]),
6
password: new FormControl(null, [Validators.required,
Validators.maxLength(8)]),
7
age: new FormControl(null, [ageRangeValidator(this.min, this.max)])
8
});
9
On the template, the custom validator can be used like any other
validator. We are using ageRange validation to show or hide an error
message:
In this case, if the user does not enter an age between 10 and 20, the
error message will be shown as seen below:
And there you have it: how to create a custom validator for Angular
Reactive Forms.
Angular 15 new features ??
(1) Introduced new Standalone API which enable developers to
build applications without using NgModules
(2) Router and HttpClient tree-shakable standalone API
bootstrapApplication(AppComponent,{
providers : [provideRouter(appRoutes)]
});
(3) Directive Composition API : brings code reuse to another level
hostDirectives : [HasColor, {
directive : CdkMenu,
inputs : [‘cfk’],
outputs : [‘pld’]}]
(4) Angular image directive has been introduced
(5) Functional Router Guards :
Const route = {
path : ‘admin’,
canActivate : [()=> inject(LoginService).isLogged()]
}
(1) What's difference between for of and for
in ?
(2) What's difference between subject n
observable?
(3) What r generic types in angular?
(4) What's difference between formbuilder
and formGroup?
(5) Remove dynamic validation from form ?
(6) FormArray in angular?
(7) What is change detector reference class
in angular ?
(8) 10 rxjs operators : map, take, takeuntill,
forkjoin, pipe,takewhile, interval, range,
filter , fromevent , debounce
(9)What is view encapsulation ?
(i) emulated : (default) styles from main
html propagate to component
(ii) ShadowDom : styles from main html do
not propagate to component
(iii) none : styles from component
propagate back to main html and can be
seen on all components on the page
(10) What is Ngzone ?
(11) What is resolver in angular
(12) What is view child and view children
(14) What is two way data binding?
(15) What is DI and how angular handling
DI?
(16) What is lazy loading and how can we
achieve this?
(17) What is content Projection?
(18) What are observables and promises
which one to use in angular?
(19) How do u transfer the data between
components? * What is ng-content?
(20) What is the usagleof ngOnChanges
lifecycle hooks?
(21) What is the difference between
constructor and ngOnInit?
(22) Can we write a class in angular without
using a constructor?
(23) What is difference between attribute
and structural directives?
(24) Which module we use in our module to
use ngIf or ngFor?
(25) What are the angular provided modules
we use in our app?
(26) What is the difference between form
builder and form control?
(27) Let suppose we have a text field and
that is name, and we have to setup a
validation to accept only 5 chars so how can
we achieve this by template driven forms. If
we want to show the error message then
how can we do it.
(28) How do you set the value of form
control in ts file? * Suppose we have an API
url so how can we use it to get the data?
(29) What is the use of httpInterceptor
Class?
(30) Which method of httpClient u will use to
get the data?
(31) If we get the response from the API and
want to filter the result what would be
another function from angular we have
rather that forEach?
(32) Have you used rxjs operator in your
application?
(33) Let suppose we have three API urls as
per first response, we need to call second
and as per second response we need to call
third API. if there would we error then on
third api call we need to show the error,
what would be the best approach for this.
Can we use rxjs operator in this issue? *
What is the difference between template
driven form and reactive based approach?
(34) What is router outlet.
(35) What is the difference between forChild
and forRoot?
(36) What is pathMatch in route?
(37) What are the guards? And what is
canLoad guard?
(38) Have u written test cases in angular?
(39) How can we deploy our web app?
(40) What is PWA? Web Push Notifications |
Service Worker
(41) How can we use authentication in
Routes?
(42) What are the pipes and how can create
custom pipes?
(43) How can we use common css files for
multiple components? Lifecycle of
components?
(44) How do we handle centralized error
tracking in angular ?
(45) Whats the difference between ngOninit
and ngOnChanges and ngDocheck ?
(Ans) ngOnChanges is fired when value on
the template changes and ngDocheck is
fired when change detection happens,
whenever @input or @output values are
changed it has the previous value and
current value if it finds change in this values
, change detection is fired
(46) How to create custom directive ?
(47) Name rxjs operators ?
(Ans) map,first,last,distinct,debounce,min,
max,count, reduce take, takewhile,
skip,skipwhile,range, pipe, filter,throwerror,
catcherror, forkjoin,of,zip,tap
(48) How do we use lazy loading with guards
?
(Ans) We can use canload authguard to
check user is authenticated or not, suppose
we are using JWT Token we can save it to
sessionStorage of browser that will say
whether user is logged in or not, depending
on that user will be redirected to login or
dashboard
(49) How does change detection work in angular ?
(Ans) We have 2 techniques (a) OnPush (b) Default
In default, if we make changes inn DOM, default
CDetection is triggered which tries to render
changes in the DOM, angular has zone.js which take
are of this, it tries to compare previous and current
changes and if it find any difference CDetection is
triggered
(50) Angular Material ?