Angular interview questions and answers 👇

  1. Angular General Interview Questions

Angular General Interview Questions

What Are Directives in Angular?

View answer

With directives, developers can write application-specific custom HTML syntax. The new language is written in the DOM, and the Angular compiler executes the directive functions when it finds a new HTML syntax. There are three types of directives – attribute, component, structural.

How Is Dependency Injection (DI) Done in Angular?

View answer

In Angular, a class asks for services or objects when it is instantiated, which means if a class is invoked, it doesn’t create any objects, rather it depends on an external source to instantiate objects, services, or parameters. In this process, an injectable service is created and registered. Injectors can be configured in three different ways,

  • @Injectable() decorator for the service.
  • @NgModule for NgModule.
  • @Component for the component.

What Is the Primary Language Used in Angular?

View answer

Angular is based on TypeScript and HTML. HTML is used for the template, and TypeScript (a superset of JavaScript) is used for components.

What Is Data Binding?

View answer

Data binding is used to connect the application data and DOM i.e. components with the template.

What are the key components of Angular?

View answer

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 components?

View answer

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.

What is a template?

View answer

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.

What is a module?

View answer

Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application.

What is metadata?

View answer

Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators.

What is a service?

View answer

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.

What is the purpose of async pipe?

View answer

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.

What is the purpose of ngFor directive?

View answer

We use Angular ngFor directive in the template to display each item in the list.

What is the purpose of ngIf directive?

View answer

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 truth/false condition.

What is interpolation?

View answer

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.

What are template expressions?

View answer

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.

What are template statements?

View answer

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

How do you categorize data binding types?

View answer

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

What are pipes?

View answer

A pipe takes in data as input and transforms it to a desired output.

What is a parameterized pipe?

View answer

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.

What is the difference between pure and impure pipe?

View answer

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 are observables?

View answer

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?

View answer

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.

What are the benefits of HttpClient?

View answer

  • Contains testability features
  • Provides typed request and response objects
  • Intercept request and response
  • Supports Observalbe APIs
  • Supports streamlined error handling

What is RxJS?

View answer

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.

What is subscribing?

View answer

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.

What is an observable?

View answer

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.

What is an observer?

View answer

Observer is an interface for a consumer of push-based notifications delivered by an Observable.

What is multicasting?

View answer

Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution.

What will happen if you do not supply handler for observer?

View answer

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?

View answer

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 are custom elements?

View answer

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?

View answer

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.

What are the mapping rules between Angular component and custom element?

View answer

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

What are dynamic components?

View answer

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?

View answer

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?

View answer

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.

What is Angular Router?

View answer

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?

View answer

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

What are the router imports?

View answer

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?

View answer

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,

What are router links?

View answer

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.

What are active router links?

View answer

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.

What is router state?

View answer

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.

What are router events?

View answer

During each navigation, the Router emits navigation events through the 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?

View answer

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.

What is the purpose of Wildcard route?

View answer

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 }

Do I need a Routing Module always?

View answer

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.

What is Angular Universal?

View answer

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?

View answer

Angular offers two ways to compile your application,

  • Just-in-Time (JIT)
  • Ahead-of-Time (AOT)

What is JIT?

View answer

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?

View answer

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

Why do we need compilation process?

View answer

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 ways to control AOT compilation?

View answer

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?

View answer

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.

Can I use arrow functions in AOT?

View answer

No, Arrow functions or lambda functions can’t be used to assign values to the decorator properties.

What is the purpose of metadata json files?

View answer

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?

View answer

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?

View answer

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.

What is metadata rewriting?

View answer

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?

View answer

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.

What is type narrowing?

View answer

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.

How do you describe various dependencies in angular application?

View answer

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?

View answer

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?

View answer

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?

View answer

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?

View answer

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 is State function?

View answer

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.

What is Style function?

View answer

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.

What is transition function?

View answer

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.

What is a service worker and its role in Angular?

View answer

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 is Angular Ivy?

View answer

Angular Ivy is a new rendering engine for Angular. You can choose to opt in a preview version of Ivy from Angular version 8.

What are the features included in ivy preview?

View answer

  • 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?

View answer

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.

What is Angular Language Service?

View answer

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.

Is there any editor support for Angular Language Service?

View answer

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 has a language service plugin model.

What are the limitations with web workers?

View answer

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?

View answer

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?

View answer

A builder function ia 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?

View answer

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?

View answer

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?

View answer

  • 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?

View answer

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?

View answer

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?

View answer

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?

View answer

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?

View answer

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.

What is Angular DSL?

View answer

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?

View answer

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.

What is Bazel tool?

View answer

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?

View answer

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

What is platform in Angular?

View answer

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?

View answer

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.

What is the purpose of differential loading in CLI?

View answer

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.

What is lazy loading?

View answer

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.

What are workspace APIs?

View answer

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.

How do you upgrade angular version?

View answer

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?

View answer

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


yarn add @angular/material @angular/cdk @angular/animations

What is NgUpgrade?

View answer

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 to use polyfills in Angular application?

View answer

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 is the reason to deprecate Web Tracing Framework?

View answer

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 schematic?

View answer

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?

View answer

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?

View answer

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 is Angular security model for preventing XSS attacks?

View answer

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?

View answer

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?

View answer

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 support it?

View answer

Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM. Yes, Angular suppports sanitization. It sanitizes untrusted values for HTML, styles, and URLs but sanitizing resource URLs isn't possible because they contain arbitrary code.

Is safe to use direct DOM API methods in terms of security?

View answer

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?

View answer

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?

View answer

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.

What are Http Interceptors?

View answer

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.

How does Angular simplify Internationalization?

View answer

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.

What is the purpose of i18n attribute?

View answer

The Angular i18n attribute marks translatable content. It is a custom attribute, recognized by Angular tools and compilers. The compiler removes it after translation.

What is select ICU expression?

View answer

ICU expression is 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.

What is an angular library?

View answer

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

What is AOT compiler?

View answer

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.

What is TestBed?

View answer

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?

View answer

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?

View answer

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.

What is the purpose of hidden property?

View answer

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.

What is the difference between ngIf and hidden property?

View answer

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 index property in ngFor directive?

View answer

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.

What is the purpose of ngSwitch directive?

View answer

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.

What is safe navigation operator?

View answer

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.

What are the list of template expression operators?

View answer

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?

View answer

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?

View answer

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.

Is it necessary for bootstrapped component to be entry component?

View answer

Yes, the bootstrapped component needs to be an entry component. This is because the bootstrapping process is an imperative process.

Why is not necessary to use entryComponents array every time?

View answer

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?

View answer

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.

Are all components generated in production build?

View answer

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?

View answer

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?

View answer

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?

View answer

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.

View answer

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?

View answer

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

What are the imported modules in CLI generated feature modules?

View answer

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 possible errors with declarations?

View answer

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?

View answer

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 are the types of feature modules?

View answer

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 the recommendation for provider scope?

View answer

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.

What are the different ways to remove duplicate service registration?

View answer

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?

View answer

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?

View answer

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.

Can I share services using modules?

View answer

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.

What is ngcc?

View answer

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?

View answer

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?

View answer

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?

View answer

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.

What is a zone context?

View answer

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.

How do you configure injectors with providers at different levels?

View answer

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.

What is an optional dependency?

View answer

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.

What are the types of injector hierarchies?

View answer

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?

View answer

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.

What are dynamic forms?

View answer

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?

View answer

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.

What is the purpose of FormBuilder?

View answer

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.

What Is the Digest Cycle?

View answer

Digest cycle is the process of monitoring watchlist to track the changes in the value of the watch variable. The digest cycle is implicitly triggered, but we can also trigger it manually using $apply() function.

What Are the Special Transition States?

View answer

Special transition states are wildcard (*) and void. Wildcard matches any animation state. The void state is used to configure transitions for elements entering or leaving a page.

What Is Package.json? Explain its Purpose.

View answer

With json package, it becomes easy to manage the project dependencies. We can mention details like the version, language etc… in package.json. For example, if typescript is used in our project, we can mention typescript and its version in package.json. Examples are metadata.json, tsconfig.json etc…

What Does {{}} Represent? What Is It Used For?

View answer

The double curly braces represent interpolation. It is a special syntax. Angular converts it into property binding. You can think of it as an alternate for property binding. The name of the component is written inside the inner curly braces. During execution, the name is replaced by the actual string value of the property.

What Does the Representation [()] Mean?

View answer

This is a representation for ngModel used for two-way data binding. It is written as [(ngModel)] = “propertyvalue”.

What Is the Single Page Application? How Is It Different From Traditional Web Technology?

View answer

In a single page application (SPA), only the home page (index.html) is maintained throughout even though the URL keeps on changing. It is faster and easier to implement when compared with traditional web technology. In traditional technology, every time a user makes a request, the request is passed on to the server. This takes more time.

What Do You Know About the NPM Package?

View answer

The components, framework and CLI used by Angular applications are packaged as npm packages. Npm packages can be downloaded using the npm CLI client.

What is a provider in Angular?

View answer

A provider is a configurable service in Angular. It is an instruction to the Dependency Injection system that provides information about the way to obtain a value for a dependency. It is an object that has a $get() method which is called to create a new instance of a service. A Provider can also contain additional methods and uses $provide in order to register new providers.

What is the difference between a service() and a factory()?

View answer

A service() in Angular is a function that is used for the business layer of the application. It operates as a constructor function and is invoked once at the runtime using the ‘new’ keyword. Whereas factory() is a function which works similar to the service() but is much more powerful and flexible. factory() are design patterns which help in creating Objects.

Explain jQLite.

View answer

jQlite is also known as jQuery lite is a subset of jQuery and contains all its features. It is packaged within Angular, by default. It helps Angular to manipulate the DOM in a way that is compatible cross-browser. jQLite basically implements only the most commonly needed functionality which results in having a small footprint.

What are the different types of filters in Angular?

View answer

Below are the various filters supported by Angular:

  • currency: Format a number to a currency format.
  • 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.
  • limit: To Limits an array/string, into a specified number of elements/characters.
  • lowercase: Format a string to lower case.
  • number: Format a number to a string.
  • orderBy: Orders an array by an expression.
  • uppercase: Format a string to upper case.

What is Transpiling in Angular?

View answer

Transpiling in Angular refers to the process of conversion of the source code from one programming language to another. In Angular, generally, this conversion is done from TypeScript to JavaScript. It is an implicit process and happens internally.

What is transclusion in Angular?

View answer

The transclusion in Angular allows you to shift the original children of a directive into a specific location within a new template. The ng directive indicates the insertion point for a transcluded DOM of the nearest parent directive that is using transclusion. Attribute directives like ng-transclude or ng-transclude-slot are mainly used for transclusion.

List some tools for testing angular applications.

View answer

  • Karma
  • Angular Mocks
  • Mocha
  • Browserify
  • Sion

What do you understand by REST in Angular?

View answer

REST stands for REpresentational State Transfer. REST is an API (Application Programming Interface) style that works on the HTTP request. In this, the requested URL pinpoints the data that needs to be processed. Further ahead, an HTTP method then identifies the specific operation that needs to be performed on that requested data. Thus, the APIs which follows this approach are known as RESTful APIs.

What is string interpolation in Angular?

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

What is [(ngModel)] used for?

View answer

Two-way data binding.

What is the use of codelyzer?

View answer

All enterprise applications follows a set of coding conventions and guidelines to maintain code in better way. Codelyzer is an open source tool to run and check whether the pre-defined coding guidelines has been followed or not. Codelyzer does only static code analysis for angular and typescript project.

Codelyzer runs on top of tslint and its coding conventions are usually defined in tslint.json file. Codelyzer can be run via angular cli or npm directly. Editors like Visual Studio Code and Atom also supports codelyzer just by doing a basic settings.

Explain the styling form that ngModel adds to CSS classes.

View answer

NgModel adds these CSS classes to allow styling of form. Validation classes of AngularJS are:

  • ng- valid
  • ng- invalid
  • ng-pristine
  • ng-dirty

What is BOM(Browser Object Model)?

View answer

BOM or Browser Object Model consists of history, object navigator, screen location, etc. It specifies the global browser objects like console, local storage, and window.

Explain "$rootScope" in AngularJS.

View answer

"$rootScope" is a scope that is created on the DOM (Document Object Model) element.

An application can have only one $rootScope that shares, among other components. It has the ng-app directive. Other scopes are called as its child scope. It can watch expressions as well as propagate events.

Define ECMAScript.

View answer

ECMAScript (European Computer Manufacturer's Association) is a standard for scripting languages. JavaScript uses ECMAScript as a core language. Developers can take help of it for writing client-side scripting on the world wide web and or server applications and services. ECMAScript has numerous features like functional, prototype, dynamic, and structured features.

What is a Traceur Compiler?

View answer

Traceur is a JavaScript compiler that uses classes, generators, and other features from ECMAScript.