Angular Interview Questions
Angular Interview Questions
Version AngularJS was the very first The later Angular versions were a complete
version initially released in 2010. It rewrite of AngularJS. For example, Angular 2 was
was a browser-side JavaScript initially released in 2016. There is nothing common
used within HTML code and between Angular2
created a revolution in web and AngularJS except the core developer's team.
application development. It is After that, Angular 6, Angular 7, Angular 8,
popularly known as AngularJS. Angular 9, and Angular 10 were released that are
very similar to each other.
These later versions are known as Angular.
Architecture AngularJS supports the MVC Angular uses components and directives.
design model.
Expression In AngularJS, a specific ng Angular uses () for event binding and [] for
Syntax directive is required for the property binding.
image/property and an event.
Structure It is the first and basic version, so It has a very simplified structure that makes the
it is very easy to manage. development and maintenance of large
applications very easy.
Speed It is slower because of its limited It is faster than AngularJS because of its upgraded
features. features.
Support It doesn't provide support or new It provides active support, and frequent new
updates anymore. updates are made.
5) What are the biggest advantages of using Angular?
Following is the list of the biggest advantages of using the Angular framework:
Syntax:
{{ expression }}
1. The most crucial difference between Angular expressions and JavaScript expressions is
that the Angular expressions allow us to write JavaScript in HTML. On the other hand, the
JavaScript expressions don't allow.
2. The Angular expressions are evaluated against a local scope object. On the other hand,
the JavaScript expressions are evaluated against the global window object. We can
understand it better with an example. Suppose we have a component named test:
1. import { Component, OnInit } from '@angular/core';
2. @Component({
3. selector: 'app-test',
4. template: `
5. <h4>{{message}}</h4>,
6. styleUrls: ['./test.component.css']
7. })
8. export class TestComponent implements OnInit {
9. message:string = ?Hello world?;
10. constructor() { }
11. ngOnInit() {
12. }
13. }
In the above example, we can see that the Angular expression is used to display the
message property. In the present template, we are using Angular expressions, so we
cannot access a property outside its local scope (in this case, TestComponent). This proves
that Angular expressions are always evaluated based on the scope object rather than the
global object.
3. The Angular expressions can handle null and undefined, whereas JavaScript expressions
cannot.
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <title>JavaScript Test</title>
7. </head>
8. <body>
9. <div id="foo"><div>
10. </body>
11. <script>
12. 'use strict';
13. let bar = {};
14. document.getElementById('foo').innerHTML = bar.x;
15. </script>
16. </html>
After running the above code, you see undefined displayed on the screen. Although it's
not ideal to leave any property undefined, the user does not need to see this.
In the above example, you will not see undefined being displayed on the screen.
In the above example, we have used a predefined pipe called lowercase, which transforms
all the letters in lowercase. If you run the above example, you will see the output displayed
as "hello javatpoint".
ADVERTISEMENT
ADVERTISEMENT
On the other hand, JavaScript does not have the concept of pipes.
1. "build": {
2. "builder": "@angular-devkit/build-angular:browser",
3. "options": {
4. "outputPath": "dist/angular-starter",
5. "index": "src/index.html",
6. "main": "src/main.ts",
7. "polyfills": "src/polyfills.ts",
8. "tsConfig": "tsconfig.app.json",
9. "aot": false,
10. "assets": [
11. "src/favicon.ico",
12. "src/assets"
13. ],
14. "styles": [
15. "./node_modules/@angular/material/prebuilt-themes/deeppurple-
amber.css",
16. "src/style.css"
17. ]
18. }
19. }
When the application enters the build section, the options object's main property defines
the entry point of the application. The application's entry point is main.ts, which creates a
browser environment for the application to run and calls a function called
bootstrapModule, which bootstraps the application.
These two steps are performed in the following order inside the main.ts file:
The AppModule is declared in the app.module.ts file. This module contains declarations
of all the components.
Now, 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.
1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>Angular</title>
6. <base href="/">
7. <meta name="viewport" content="width=device-width, initial-scale=1">
8. </head>
9. <body>
10. <app-root></app-root>
11. </body>
12. </html>
The HTML template of the root component is displayed inside the <app-root> tags.This
is the way how every angular application works.
Extraordinary Built-in Features: Angular provides several out of the box built-in features
like routing, state management, RxJS library, Dependency Injection, HTTP services, etc.
That's why the developers do not need to look for the above-stated features separately.
ADVERTISEMENT
Declarative UI: Angular has declarative UI. It uses HTML to render the UI of an application
as it is a declarative language. It is much easier to use than JavaScript.
12) What are the different Lifecycle hooks of Angular? Explain them
in short.
When the Angular components are created, they enter their lifecycle and remain when
they are destroyed. Angular Lifecycle hooks are used to check the phases and trigger
changes at specific phases during the entire duration.
ngOnChanges( ): This method is called when one or more input properties of the
component are changed. The hook receives a SimpleChanges object containing the
previous and current values of the property.
ngOnInit( ): This is the second lifecycle hook. It is called once, after the ngOnChanges
hook. It is used to initialize the component and sets the input properties of the
component.
ngDoCheck( ): This hook is called after ngOnChanges and ngOnInit and is used to detect
and act on changes that Angular cannot detect. In this hook, we can implement our
change detection algorithm.
ngAfterContentInit( ): This hook is called after the first ngDoCheck hook. This hook
responds after the content gets projected inside the component.
ngOnDestroy( ): This hook is called just before Angular destroys the component. This is
used to clean up the code and detach event handlers.
In the above hooks we have described, the ngOnInit hook is the most often used hook.
Let's see how to use the ngOnInit hook. If you have to process a lot of data during
component creation, it's better to do it inside the ngOnInit hook rather than the
constructor:
In the above code, you can see that we have imported OnInit, but we have used the
ngOnInit function. This is how we can use the rest of the hooks as well.
14) What is the reason for using the AOT compiler in Angular?
An Angular application is made of several components and their HTML templates.
Because of these Angular components and templates, the browsers are not able to
understand them directly. So, Angular applications require a compilation process before
they run in a browser. That's why AOT compilers are required.
The rendering is faster: When we use the AOT compiler, the browser gets a pre-
compiled version of the application to download. Here, the browser loads executable code
to render the application immediately, without waiting to compile the app first.
The Angular framework's download size is smaller: AOT facilitates you not to
download the Angular compiler if the app is already compiled. The compiler is roughly
half of Angular itself, so omitting it dramatically reduces the application payload.
Fewer asynchronous requests: The compiler is used to inline external HTML templates
and CSS style sheets within the application JavaScript so, it eliminates separate AJAX
requests for those source files.
Detect template errors earlier: While using the AOT compiler, developers can easily
detect and report template binding errors during the build step before users can see
them.
Better security: AOT provides better security because it compiles HTML templates and
components into JavaScript files before they are served to the client. Because there are
no templates to read and no risky client-side HTML or JavaScript evaluation, so the
chances for injection attacks are very rare.
17) What is the main difference between JIT and AOT in Angular?
Following are the main differences between JIT and AOT compiler in Angular:
o Just-in-Time (JIT) compiler compiles our app in the browser at run-time while
Ahead-of-Time (AOT) compiler is used to compile your app at build time on the
server.
o The JIT compilation runs by default when you run the ng build (build only), or ng
serve (build and serve locally) CLI commands. This is used for development. On the
other hand, we have to include the --aot option with the ng build or ng serve
command for AOT compilation.
o JIT and AOT are both two ways used to compile code in an Angular project. JIT
compiler is used in development mode while AOT is used for production mode.
o JIT is easy to use. We can easily implement features and debug in JIT mode because
here we have a map file while AOT does not. On the other hand, the biggest
advantage of using AOT for production is that it reduces the bundle size for faster
rendering.
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.
Promise Observable
It emits a single It emits multiple values over a period of time.
value.
Not Lazy Lazy. An observable is not called until we subscribe to the observable.
When you run the above Observable, you can see the following messages displayed in
the following order:
Here, you can see that observables are lazy. Observable runs only when someone
subscribes to them. That's why the message "Before subscribing an Observable" is
displayed ahead of the message inside the observable.
When you run the above Promise, you will see the messages displayed in the following
order:
Here, you can see that the message inside Promise is displayed first. This means that the
Promise runs first, and then the method is called.
The next difference between them is that Promises are always asynchronous; even when
the Promise is immediately resolved. On the other hand, an Observable can be both
synchronous and asynchronous.
In the case of the above example, observable is synchronous. Let's see the case where an
observable can be asynchronous:
When you run the above observable, you will see the messages in the following order:
The client-side frameworks like Angular were introduced to overcome the above
problems. It provides developers many benefits over VanilaJS and jQuery by providing a
new feature called components for handling separation of concerns and dividing code
into smaller bits of information.
Note: We can also develop dynamic websites and SPAs (Single Page Applications) using
VanillaJS, and jQuery but by doing so, the development process becomes slower.
To use Angular CLI, we have to install it by using the following npm command:
Following is a list of some useful commands which would be very helpful while
creating angular projects:
See the following example where we are going to load both Employee and Order feature
modules lazily.
See the following example of how we can import them in the app module:
Syntax:
1. <router-outlet></router-outlet>
On the other hand, a RouterLink is a directive on the anchor tags that gives the router
control over those elements. Since the navigation paths are fixed, you can assign string
values to router-link directive as below,
Syntax:
1. <h1>Angular Router</h1>
2. <nav>
3. <a routerLink="/todosList" >List of todos</a>
4. <a routerLink="/completed" >Completed todos</a>
5. </nav>
6. <router-outlet></router-outlet>
29) What are the different router events used in Angular Router?
During each navigation, the Router emits navigation events through the Router.events
property. It allows us to track the lifecycle of the route.
o NavigationStart
o RouteConfigLoadStart
o RouteConfigLoadEnd
o RoutesRecognized
o GuardsCheckStart
o ChildActivationStart
o ActivationStart
o GuardsCheckEnd
o ResolveStart
o ResolveEnd
o ActivationEnd
o ChildActivationEnd
o NavigationEnd
o NavigationCancel
o NavigationError
1. <h1>Angular Router</h1>
2. <nav>
3. <a routerLink="/todosList" routerLinkActive="active">List of todos</a>
4. <a routerLink="/completed" routerLinkActive="active">Completed todos</a>
5. </nav>
6. <router-outlet></router-outlet>
1. @Component({templateUrl:'template.html'})
2. class MyComponent {
3. constructor(router: Router) {
4. const state: RouterState = router.routerState;
5. const root: ActivatedRoute = state.root;
6. const child = root.firstChild;
7. const id: Observable<string> = child.params.map(p => p.id);
8. //...
9. }
10. }
o Making an Angular application render on the server-side can provide a better user
experience. By using this, first-time users can instantly see a view of the application.
So, it can be used to provide better UI.
o It can lead to a better SEO for your application. The reason is that many search
engines expect pages in plain HTML. So, Angular Universal can ensure that your
content is available on every search engine, and it is good for better SEO.
o The server-side rendered applications load faster than normal pages. It is because
the rendered pages are available to the browser sooner.
You can write an error message to give the user some meaningful feedback instead of
displaying the raw error object returned from HttpClient.
o Manual bootstrapping
o Automatic bootstrapping
Component Directive
Components are generally used for creating UI Directives are generally used for adding
widgets. behavior to an existing DOM element.
It is used to break up the application into smaller It is used to design re-usable components.
parts called components.
Only one component is allowed to be used per Multiple directives are allowed to be used
DOM element. per DOM element.
o Model
o View
o ViewModel
Model: The Model consists of the structure of an entity and specifies the approach. In
simple words, we can say that the model contains data of an object.
View: The View is the visual layer of the application. It specifies the structure, layout, and
appearance of what a user sees on the screen. It displays the data inside the Model,
represents the model, and receives the user's interaction with the view in the form of
mouse clicks, keyboard input, screen tap gestures, etc., and forwards these to the
ViewModel via the data binding properties. In Angular terms, the View contains the HTML
template of a component.
See the following example where a time observable continuously updates the view for
every 2 seconds with the current time.
Example:
1. @Component({
2. selector: 'async-observable-pipe',
3. template: `<div><code>observable|async</code>:
4. Time: {{ time | async }}</div>`
5. })
6. export class AsyncObservablePipeComponent {
7. time = new Observable(observer =>
8. setInterval(() => observer.next(new Date().toString()), 2000)
9. );
10. }
Angular services offer some functions that can be invoked from an Angular component,
such as a controller or directive.
See the following example how we can use ngOnInit by implementing OnInit interface as
follows:
Observer: Any object that has to be notified when the state of another object changes is
called an observer. An observer is an interface for push-based notifications delivered by
an Observable.
1. interface Observer<T> {
2. closed?: boolean;
3. next: (value: T) => void;
4. error: (err: any) => void;
5. complete: () => void;
6. }
The handler that implements the observer interface for receiving observable notifications
is passed as a parameter for observable as follows:
1. myObservable.subscribe(myObserver);
Note: If you don't use a handler for a notification type, the observer ignores notifications of
that type.
47) What is the use of Angular filters? What are its distinct types?
Filters are an essential part of Angular that helps in formatting the expression value to
show it to the users. We can easily add filters to services, directives, templates, or
controllers. We can also create personalized filters as per requirements. These filters allow
us to organize the data in such a way that only the data that meets the respective criteria
are displayed. Filters are placed after the pipe symbol ( | ) while used in expressions.
Component Directives: The component directives are used to form the main class in
directives. To declare these directives, we have to use the @Component decorator instead
of @Directive decorator. These directives have a view, a stylesheet and a selector property.
Structural directives: These directives are generally used to manipulate DOM elements.
The structural directive has a ' * ' sign before them. We can apply these directives to any
DOM element.
*ngIf Structural Directive: *ngIf is used to check a Boolean value and if it's truthy, the
div element will be displayed.
*ngFor Structural Directive: *ngFor is used to iterate over a list and display each item of
the list.
Attribute Directives: The attribute directives are used to change the look and behavior
of a DOM element. Let's create an attribute directive to understand it well:
Go to the command terminal, navigate to the directory of the angular app and type the
following command to generate a directive:
1. ng g directive yellowBackground
This will generate the following directive. Manipulate the directive to look like this:
Now, you can easily apply the above directive to any DOM element:
String interpolation and property binding both are examples of one-way data binding.
They allow only one-way data binding.
String Interpolation: 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, {{ 5+5 }} will be evaluated by Angular, and the output will be 10. This
output will be displayed inside the HTML template.
Property Binding: Property binding is used to bind the DOM properties of an HTML
element to a component's property. In property binding, we use the square brackets [ ]
syntax.
Better User Experience: It enables users to see the view of the application instantly.
Better SEO: Angular Universal ensures that the content is available on every search
engine leading to better SEO.
Load Faster: Angular Universal ensures that the render pages available to the browsers
sooner to make the loading faster server-side application loads faster.
Architecture Angular works on the MVC architecture and Backbone.js makes use of the MVP
makes use of two-way data binding for driving architecture and doesn't provide any data
application activity. binding process.
Data Binding Angular is a little bit complex because it uses On the other hand, Backbone.js has a
a two-way data binding process. simple API because it doesn't have any data
binding process.
DOM Angular's main focus is on valid HTML and Backbone.js follows the direct DOM
dynamic elements that imitate the underlying manipulation
data for rebuilding the DOM as per the approach for representing data and
specified rules and then work on the updated application architecture changes.
data records.
Performance Because of its two-way data binding Backbone.js is quite a significant upper
functionality, Angular provides powerful hand in performance over Angular in small
performance for both small and large projects. data sets or small web pages. It is not
recommended for larger web pages or
large data sets due to the absence of any
data binding process.
Templating Angular supports templating via dynamic Backbone.js uses Underscore.js templates
HTML attributes. You can add them to the that aren't fully-featured as Angular
document to develop an easy to understand templates.
application at a functional level.
Testing The testing approach is lengthy for Angular The testing approach is completely
Approach because it is preferred for building large different for Backbone.js because it is ideal
applications. for developing smaller webpages or
It uses unit testing. applications.
Community The angular framework is developed and Backbone.js also receives a good level of
Support maintained by Google, so it receives great community support, but it only documents
community support. Here, extensive on Underscore.js templates, not much else.
documentation is available.