AngularJS (67 Blogs) Become a Certified Professional

70+ Angular Interview Questions for Freshers and Experienced

Last updated on Oct 05,2024 607.9K Views

Swatee Chand
Sr Research Analyst at Edureka. A techno freak who likes to explore... Sr Research Analyst at Edureka. A techno freak who likes to explore different technologies. Likes to follow the technology trends in market and write...
1 / 1 Blog from AngularJS Interview Questions

In this Angular Interview Questions article, I am going to list some of the most important Angular Interview Questions and Answers which will set you apart in the interview process in 2021. With over 7.2 Million repositories on GitHub, Angular is known as the Swiss army knife of frontend developers! This is the reason why Angular Certification Training Course is the most in-demand certification in scripting domain.

We have compiled a list of top Angular interview questions which are classified into 3 sections, namely:

As an Angular professional, it is essential to know the right buzzwords, learn the right technologies and prepare the right answers to commonly asked Angular Interview Questions. Here’s a definitive list of top Angular Interview Questions that will guarantee a breeze-through to the next level.

In case you attended any Angular interview recently, or have additional questions beyond what we covered, we encourage you to post them in our QnA Forum. Our expert team will get back to you at the earliest.  

So let’s get started with the first set of basic Angular Interview Questions.

Beginners Level – Angular Interview Questions

1. Differentiate between Angular and AngularJS.

FeatureAngularJSAngular
ArchitectureSupports MVC design modelUses components and directives
LanguageRecommended Language: JavaScript Recommended Language: TypeScript
Expression SyntaxSpecific ng directive is required for the image/property and an eventUses () to bind an event and [] for property binding
Mobile SupportDoesn’t provide any mobile supportProvides mobile support
Routing$routeprovider.when() is used for routing configs@RouteConfig{(…)} is used for routing config
Dependency InjectionDoesn’t supports the concept of Dependency InjectionSupports hierarchical Dependency Injection with a unidirectional tree-based change detection
StructureLess manageableSimplified structure and makes the development and maintenance of large applications easier
SpeedWith two-way data binding development effort and time are reducedFaster than AngularJS with upgraded features
SupportNo support or new updates are provided anymoreActive support and frequent new updates are made

 

2. What is Angular?

Angular is an open-source front-end web framework. It is one of the most popular JavaScript frameworks that is mainly maintained by Google. It provides a platform for easy development of web-based applications and empowers the front end developers in curating cross-platform applications. It integrates powerful features like declarative templates, an end to end tooling, dependency injection and various other best practices that smoothens the development path. Check out this Full Stack Developer Course today to learn more about Angular.

3. What are the advantages of using Angular?

A few of the major advantages of using Angular framework are listed below:

  • It supports two-way data-binding
  • It follows MVC pattern architecture
  • It supports static template and Angular template
  • You can add a custom directive
  • It also supports RESTfull services
  • Validations are supported
  • Client and server communication is facilitated
  • Support for dependency injection
  • Has strong features like Event Handlers, Animation, etc.

 

4. What is Angular mainly used for?

Angular is typically used for the development of SPA which stands for Single Page Applications. Angular provides a set of ready-to-use modules that simplify the development of single page applications. Not only this, with features like built-in data streaming, type safety, and a modular CLI,  Angular is regarded as a full-fledged web framework.

5. What are Angular expressions?

Angular expressions are code snippets that are usually placed in binding such as {{ expression }} similar to JavaScript. These expressions are used to bind application data to HTML

Syntax: {{ expression }}

 

6. What are templates in Angular?

Templates in Angular are written with HTML that contains Angular-specific elements and attributes. These templates are combined with information coming from the model and controller which are further rendered to provide the dynamic view to the user.

7. In Angular what is string interpolation?

String interpolation in Angular is a special syntax that uses template expressions within double curly {{ }} braces for displaying the component data. It is also known as moustache syntax. The JavaScript expressions are included within the curly braces to be executed by Angular and the relative output is then embedded into the HTML code. These expressions are usually updated and registered like watches, as a part of the digest cycle.

8. What is the difference between an Annotation and a Decorator in Angular?

Annotations in angular are “only” metadata set of the class using the Reflect Metadata library. They are used to create an “annotation” array. On the other hand, decorators are the design patterns that are used for separating decoration or modification of a class without actually altering the original source code.

9. What do you understand by controllers in Angular?

Controllers are JavaScript functions which provide data and logic to HTML UI. As the name suggests, they control how data flows from the server to HTML UI.

10. What is scope in Angular?

Scope in Angular is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in a hierarchical structure which mimics the DOM structure of the application. Scopes can watch expressions and propagate events.

11. What are directives in Angular?

A core feature of Angular, directives are attributes that allow you to writenew HTML syntax, specific to your application. They are essentially functions that execute when the Angular compiler finds them in the DOM.  The Angular directives are segregated into 3 parts:

  1. Component Directives
  2. Structural Directives
  3. Attribute Directives

12. What is data binding?

In Angular, data binding is one of the most powerful and important features that allow you to define the communication between the component and DOM(Document Object Model). It basically simplifies the process of defining interactive applications without having to worry about pushing and pulling data between your view or template and component. In Angular, there are four forms of data binding:

  1.  String Interpolation
  2. Property Binding
  3. Event Binding
  4. Two-Way Data Binding

13. What are some of the advantages of Angular over other frameworks?

FeaturesAngularOthers

Out of box features

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 to look for the above stated features separately. They are all provided with angular.

Not all the frameworks provide in-built features, some have to be externally installed.

Declarative UI

Angular uses HTML to render the UI of an application. HTML is a declarative language and is much easier to use than JavaScript.

Without declarative UI the bare minimum Javascript is time-consuming and hard to use.

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.

There could be a chance where the application might not be compatible with Google.

14. How does one share data between components in Angular?

  • Data Sharing Between Angular Components
  • Parent to Child: via Input
  • Child to Parent: via Output() and EventEmitter
  • Child to Parent: via ViewChild
  • Unrelated Components: via a Service

Parent to Child: via Input

Every time you define @Input() in the child component the information will be obtained from the master or parent component. Data model has to be always defined using interfaces before sharing data between components. Here we are defining the Product interface with productID and productName as mandatory fields and rest are optional.
Now the parent component can import the product interface. At this point a template is created. Here the template has a product id and product name. Now our aim is to share the product name with the child component. Once the product name is updated in the child component it should be reflected in the parent component also.

Child to Parent: via Output() and EventEmitter

For sharing data from child to parent we need an output decorator. In child component we have to define output decorator like this:

@Output() childToParent = new EventEmitter<String>();

Now since we can sharing the data with the parent component, the child component requires to bubble the event with value to the parent components. We can bubble the event based on a trigger point, here we are doing it by using a button click. sendToParent is called on button click.

sendToParent(name){this.childToParent.emit(name);}

Here there is an association with childtoParent property and child tag in the parent component.

<app-child [childToMaster]=product.productName (childToParent)=&rdquo;childToParent($event)&rdquo;>
</app-child>

Here, The value is received and set in the parent component.

 


childToParent(name)

{

this.product.productName=name;

}

Look! Now we can see the product name changes in parent components.

 

Sharing data between sibling components:

Use the above points and similarly share the data between siblings as well, First share data between the child and parent using the output decorator and EventEmitter. Once received data in the parent component shares it to another child component using Input decorator. Now, siblings can communicate with each other via parent components.

Sharing data using ViewChild decorator:

ViewChild allows child components to be injected into parent components. So this makes ViewChild more powerful. It allows parents to control the child’s methods and properties. But a parent can get access to the properties after viewing init events. That means we have to implement ngAfterViewInit life cycle hook in order to get the properties from parent components.

Sharing data between not related components:

Say there is no relation between the components in that case we cannot pass the data using the above mentioned methods. Generally you can encounter this when components are in different modules. There are other scenarios when you have a list of products and click on a particular product and then redirect to product details components. In these kinds of scenarios, Data Service is used to share data between components.

15. What is the purpose of a filter in Angular?

Filters in Angular are used for formatting the value of an expression in order to display it to the user. These filters can be added to the templates, directives, controllers or services. Not just this, you can create your own custom filters. Using them, you can easily organize data in such a way that the data is displayed only if it fulfils certain criteria. Filters are added to the expressions by using the pipe character |, followed by a filter.

16. Explain MVVM architecture

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.

MVVM Architecture - Angular Interview Questions - Edureka

  1. Model: It represents the data and the business logic of an application, or we may say it contains the structure of an entity. The business logic part of of the MVVM involves: Local and remote data source, model classes and repository.
  2. View: View is basically the visual layer of the application. It consists of the UI Code(which is present in Angular- HTML template of a component). This UI code first sends the user action to the ViewModel but does not get any response back directly. There has to be a subscription to the observables by which ViewModel will give the response back to the UI Code.
  3. ViewModel: This is an abstract layer of the application which acts as a bridge between the View and Model(business logic). This does not have any direct reference to the View, and hence does not have any clue as to which View has to use it. View and ViewModel are connected with data-binding so, any change in the View the ViewModel notes it down and changes the data inside the Model. It basically interacts with the Model and shows the observable that can be observed by the View.

Also read : How to check the angular version?

17. What are decorators in Angular?

Decorators are a design pattern that is used to separate modification or decoration of a class without modifying the original source code. In AngularJS, decorators are functions that allow a service, directive or filter to be modified prior to its usage.

Decorator that marks a class as an Angular component and provides configuration metadata that determines how the component should be processed, instantiated, and used at runtime.

18. What is Eager and Lazy Loading?

The application module i.e. AppModule is loaded eagerly before application starts. Whereas there is something called feature modules which holds all the features of each module which can be loaded in two ways namely eagerly or lazily or even preloaded in some cases.

Eager loading:
To load a feature module eagerly we need to import it into an application module using imports metadata of @NgModule decorator. Eager loading is highly used in small size applications. In eager loading, all the feature modules will be loaded before the application starts.This is the reason the subsequent request to the application will always be faster.

Lazy loading:
To load a feature module lazily we need to load it using loadChildren property in route configuration and that feature module must not be imported in the application module. Lazy loading generally is useful when the application is growing in size. In lazy loading, feature modules will be loaded on demand and hence application start will be faster.

 

19. Explain Components, Modules and Services in Angular

Modules, components and services are classes that use decorators. These decorators mark their type and provide metadata that tells Angular how to use them. The metadata for a component class associates it with a template that defines a view.

Components:
We have one or more components at the heart of every Angular App. In fact, in the real world, we create complicated apps that contain tens of components. The data, HTML markup, and logic for a view behind the view are all encapsulated in a Component. Component-based design is embraced by Angular, allowing us to work on smaller, more maintainable portions that may also be reused in different places.
Every application must have at least one component, referred to as the appcomponent or root component. Starting with the appcomponent, a real-world Angular app is effectively a tree of components.
Modules:
A module is a container that holds a collection of connected components. Every angular app contains at least one module, which we refer to as the app module. We may want to divide our modules into smaller, more maintainable modules as our application expands. As the programme expands, we will need to subdivide our app module into smaller modules, each of which will be responsible for a different section. It has components that are connected.
Service:
Angular services are singleton objects that are instantiated only once during an application’s lifetime. They include methods for preserving data during the life of an application, i.e., data is not refreshed and is always available.

20. What are Template and Reactive Forms?

Template-driven forms are those in which the logic, validations, and controls are all written in the template section of the code (html code). The template is in charge of putting up the form, validation, control, and grouping, among other things.
You can create a template form using the following command:

ng generate component template-forms

Reactive Forms: Through the attributes and methods provided with each instance, reactive forms enable access to information about a given control. When managing input validation, these properties and methods of the underlying AbstractControl class are utilised to control form state and determine when to display messages.
You can create a reactive form using the following command:

ng generate component reactive-forms

21. How do you update to Angular 12?

Inside your CLI, you can update a project with the command below:

ng update @angular/cli @angular/core

22. State some differences between Angular 11 and Angular 12

In the study of Angular version 11 vs Angular version 12, we have learned the differences in their performances, the deprecation and up-gradation in existing features that change the core structure of the framework. With the rising popularity of the framework, we are expecting a beta version around spring.

Angular 11Angular 12
TypeScript 3.9TypeScript 4.0
Enabled ES5 buildsFaster Builds
Language-service-specific compilerNgcc compiler
Optional Stricter SettingsWebpack 5 Support
Converting pre-Ivy codeAutomatic Inlining of Fonts
TSLint v6Migration to ESLint
Deprecation of ESM5 or FESM5 bundlesDeprecation of IE 9, 10, and IE mobile
Recovered Service Worker storesClear API surface
Updated to TSLib 2.9Updates on Operation Byelog
New Default Browser ConfigurationUpdated Language Service Preview

23. What is property binding and why is it important in Angular 12?

In Angular one of the ways to pass down values from a component to its template with a set value is through property binding. It is a great example of a one-way data-binding technique used to transfer data.
Syntax

<template_element [property]= 'property'>

TypeScript
So basically at the backend, as we bind a template or DOM element to a defined field, this field is defined inside the component Angular just turns the string interpolation to property binding.

24. What are the observable updates in the latest version of Angular?

  • Faster Builds
  • Angular ESLint Updates
  • Internet Explorer Updates
  • Webpack 5 Support
  • Improved Logging and Reporting
  • Updated Language Service Preview
  • Updated Hot Module Replacement (HMR) Support

 

25. What are the differences between Angular and jQuery?

FeaturesjQueryAngular
DOM ManipulationYesYes
RESTful APINoYes
Animation SupportYesYes
Deep Linking RoutingNoYes
Form ValidationNoYes
Two Way Data BindingNoYes
AJAX/JSONPYesYes

26. What is a provider in Angular?

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.

27. Explain the @Component Decorator

A component decorator(@Component) lets you mark a class as an Angular component and add metadata that controls how the component is processed, instantiated, and used at runtime. Components are the most fundamental building blocks of an Angular application’s user interface.

Intermediate Level – Angular Interview Questions

28.Does Angular support nested controllers?

Yes, Angular does support the concept of nested controllers. The nested controllers are needed to be defined in a hierarchical manner for using it in the View. 

29. How can you differentiate between Angular expressions and JavaScript expressions?

Angular ExpressionsJavaScript Expressions
1. They can contain literals, operators, and variables.1. They can contain literals, operators, and variables.
2. They can be written inside the HTML tags.2. They can’t be written inside the HTML tags.
3. They do not support conditionals, loops, and exceptions.3. They do support conditionals, loops, and exceptions.
4.  They support filters.4.  They do not support filters.

30. List at down the ways in which you can communicate between applications modules using core Angular functionality.

Below are the most general ways for communicating between application modules using core Angular functionality :

  • Using events
  • Using services
  • By assigning models on $rootScope
  • Directly between controllers [$parent$$childHead$$nextSibling, etc.]
  • Directly between controllers [ControllerAs, or other forms of inheritance]

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

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.

32. What is the difference between $scope and scope in Angular?

  • $scope in Angular is used for implementing the concept of dependency injection (D.I) on the other hand scope is used for directive linking.
  • $scope is the service provided by $scopeProviderwhich can be injected into controllers, directives or other services whereas Scope can be anything such as a function parameter name, etc.

33. Explain the concept of scope hierarchy?

The $scope objects in Angular are organized into a hierarchy and are majorly used by views. It contains a root scope which can further contain scopes known as child scopes. One root scope can contain more than one child scopes. Here each view has its own $scope thus the variables set by its view controller will remain hidden to the other controllers. The Scope hierarchy generally looks like:

  • Root $scope
    • $scope for Controller 1
    • $scope for Controller 2
    • ..
    • $scope for Controller ‘n’

34. What is AOT?

AOT stands for Angular Ahead-of-Time compiler. It is used for pre-compiling the application components and along with their templates during the build process. Angular applications which are compiled with AOT has a smaller launching time. Also, components of these applications can execute immediately, without needing any client-side compilation. Templates in these applications are embedded as code within their components. It reduces the need for downloading the Angular compiler which saves you from a cumbersome task. AOT compiler can discard the unused directives which are further thrown out using a tree-shaking tool.

35. Explain jQLite.

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.

36. Explain the process of digest cycle in Angular?

The digest cycle in Angular is a process of monitoring the watchlist for keeping a track of changes in the value of the watch variable. In each digest cycle, Angular compares the previous and the new version of the scope model values. Generally, this process is triggered implicitly but you can activate it manually as well by using $apply().

process of digest cycle in Angular

37. What are the Angular Modules?

All the Angular apps are modular and follow a modularity system known as NgModules. These are the containers which hold a cohesive block of code dedicated specifically to an application domain, a workflow, or some closely related set of capabilities. These modules generally contain components, service providers, and other code files whose scope is defined by the containing NgModule.  With modules makes the code becomes more maintainable, testable, and readable. Also, all the dependencies of your applications are generally defined in modules only.

38. On which types of the component can we create a custom directive?

Angular provides support to create custom directives for the following:

  • Element directives − Directive activates when a matching element is encountered.
  • Attribute − Directive activates when a matching attribute is encountered.
  • CSS − Directive activates when a matching CSS style is encountered.
  • Comment − Directive activates when a matching comment is encountered

39. What are the different types of filters in Angular?

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.

40. What is Dependency Injection in Angular? 

Dependency Injection (DI) is a software design pattern where the objects are passed as dependencies rather than hard-coding them within the component. The concept of Dependency Injection comes in handy when you are trying to separate the logic of object creation to that of its consumption. The ‘config’ operation makes use of DI that must be configured beforehand while the module gets loaded to retrieve the elements of the application. With this feature, a user can change dependencies as per his requirements.

41. Differentiate between one-way binding and two-way data binding.

In One-Way data binding, the View or the UI part does not update automatically whenever the data model changes. You need to manually write custom code in order to update it every time the view changes.

1 way data binding - Angular Interview Questions - Edureka

Whereas, in Two-way data binding, the View or the UI part is updated implicitly as soon as the data model changes. It is a synchronization process, unlike One-way data binding.

2 way data binding - Angular Interview Questions - Edureka

42. What are the lifecycle hooks for components and directives?

An Angular component has a discrete life-cycle which contains different phases as it transits through birth till death. In order to gain better control of these phases, we can hook into them using the following:

  • constructor: It is invoked when a component or directive is created by calling new on the class.
  • ngOnChanges: It is invoked whenever there is a change or update in any of the input properties of the component.
  • ngOnInit: It is invoked every time a given component is initialized. This hook is only once called in its lifetime after the first ngOnChanges.
  • ngDoCheck: It is invoked whenever the change detector of the given component is called. This allows you to implement your own change detection algorithm for the provided component.
  • ngOnDestroy: It is invoked right before the component is destroyed by Angular. You can use this hook in order to unsubscribe observables and detach event handlers for avoiding any kind of memory leaks.

43. What do you understand by dirty checking in Angular?

In Angular, the digest process is known as dirty checking. It is called so as it scans the entire scope for changes. In other words, it compares all the new scope model values with the previous scope values. Since all the watched variables are contained in a single loop, any change/update in any of the variable leads to reassigning of rest of the watched variables present inside the DOM. A watched variable is in a single loop(digest cycle), any value change of any variable forces to reassign values of other watched variables in DOM

44. Differentiate between DOM and BOM.

DOMBOM
1. Stands for Document Object Model1. Stands for Browser Object Model
2. Represents the contents of a web page2. Works a level above web page and includes browser attributes
3. All the Objects are arranged in a tree structure and the document can be manipulated & accessed via provided APIs only3. All global JavaScript objects, variables & functions become members of the window object implicitly
4. Manipulates HTML documents4. Access and manipulate the browser window
5. W3C Recommended standard specifications5. Each browser has its own implementation

45. What is Transpiling in Angular?
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.

46. How to perform animation in Angular?

In order to perform animation in an Angular application, you need to include a special Angular library known as Animate Library and then refer to the ngAnimate module into your application or add the ngAnimate as a dependency inside your application module.

47. What is transclusion in Angular?

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.

48. What are events in Angular?

Events in Angular are specific directives that help in customizing the behavior of various DOM events. Few of the events supported by Angular are listed below:

  • ng-click
  • ng-copy
  • ng-cut
  • ng-dblclick
  • ng-keydown
  • ng-keypress
  • ng-keyup
  • ng-mousedown
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-mouseup
  • ng-blur

49. List some tools for testing angular applications?

  1. Karma
  2. Angular Mocks
  3. Mocha
  4. Browserify
  5. Sion

50. How to create a service in Angular?

In Angular, a service is a substitutable object that is wired together using dependency injection. A service is created by registering it in the module it is going to be executed within. There are basically three ways in which you can create an angular service. They are basically three ways in which a service can be created in Angular:

  • Factory
  • Service
  • Provider

51. What is a singleton pattern and where we can find it in Angular?

Singleton pattern in Angular is a great pattern which restricts a class from being used more than once. Singleton pattern in Angular is majorly implemented on dependency injection and in the services. Thus, if you use ‘new Object()’ without making it a singleton, then two different memory locations will be allocated for the same object. Whereas, if the object is declared as a singleton, in case it already exists in the memory then simply it will be reused.

52. What do you understand by REST in Angular?

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.

53. What is bootstrapping in Angular?

Bootstrapping in Angular is nothing but initializing, or starting the Angular app. Angular supports automatic and manual bootstrapping.

  • Automatic Bootstrapping: this is done by adding the ng-app directive to the root of the application, typically on the tag or tag if you want angular to bootstrap your application automatically. When Angular finds ng-app directive, it loads the module associated with it and then compiles the DOM.
  • Manual Bootstrapping:Manual bootstrapping provides you more control on how and when to initialize your Angular application. It is useful where you want to perform any other operation before Angular wakes up and compile the page.

54. What is the difference between a link and compile in Angular?

  • Compile function is used for template DOM Manipulation and to collect all the directives.
  • Link function is used for registering DOM listeners as well as instance DOM manipulation and is executed once the template has been cloned.

55.What do you understand by constants in Angular?

In Angular, constants are similar to the services which are used to define the global data. Constants are declared using the keyword “constant”. They are created using constant dependency and can be injected anywhere in controller or services.

56. What is the difference between a provider, a service and a factory in Angular?

ProviderServiceFactory
A provider is a method using which you can pass a portion of your application into app.configA service is a method that is used to create a service instantiated with the ‘new’ keyword.It is a method that is used for creating and configuring services. Here you create an object, add properties to it and then return the same object and pass the factory method into your controller.

57.What are Angular Global APIs?

Angular Global API is a combination of global JavaScript functions for performing various common tasks like:

  • Comparing objects
  • Iterating objects
  • Converting data

There are some common Angular Global API functions like:

  • angular. lowercase: Converts a string to lowercase string.
  • angular. uppercase: Converts a string to uppercase string.
  • angular. isString: Returns true if the current reference is a string.
  • angular. isNumber: Returns true if the current reference is a number.

 

58. What is subscribing?

In Angular, .subscribe() is basically a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
Subscribe takes 3 methods as parameters each are functions:

  • next: For each item being emitted by the observable perform this function
  • error: If somewhere in the stream an error is found, do this method
  • complete: Once all items are complete from the stream, do this method

 

Transform your design skills with our UI UX Design Course.

 

 

Advanced Level – Angular Interview Questions

59. In Angular, describe how will you set, get and clear cookies?

For using cookies in Angular, you need to include a  module called ngCookies angular-cookies.js.

To set Cookies – For setting the cookies in a key-value format ‘put’ method is used.

cookie.set('nameOfCookie',"cookieValue"); 

To get Cookies – For retrieving the cookies ‘get’ method is used.

cookie.get(‘nameOfCookie’);

To clear Cookies – For removing cookies ‘remove’ method is used.

cookie.delete(‘nameOfCookie’);

60.  If your data model is updated outside the ‘Zone’, explain the process how will you the view?

You can update your view using any of the following:

  1. ApplicationRef.prototype.tick(): It will perform change detection on the complete component tree.
  2. NgZone.prototype.run(): It will perform the change detection on the entire component tree. Here, the run() under the hood will call the tick itself and then parameter will take the function before tick and executes it.
  3. ChangeDetectorRef.prototype.detectChanges(): It will launch the change detection on the current component and its children.

61. Explain ng-app directive in Angular.

ng-app directive is used to define Angular applications which let us use the auto-bootstrap in an Angular application. It represents the root element of an Angular application and is generally declared near <html> or <body> tag. Any number of ng-app directives can be defined within an HTML document but just a single Angular application can be officially bootstrapped implicitly. Rest of the applications must be manually bootstrapped. 

Example


<span><span class="tag"><</span><span class="tag-name">div</span>&nbsp;<span class="attribute">ng-app</span>=<span class="attribute-value">"myApp"</span>&nbsp;<span class="attribute">ng-controller</span>=<span class="attribute-value">"myCtrl"</span><span class="tag">></span>
First&nbsp;Name&nbsp;:
<span class="tag"><</span><span class="tag-name">input</span>&nbsp;<span class="attribute">type</span>=<span class="attribute-value">"text"</span>&nbsp;<span class="attribute">ng-model</span>=<span class="attribute-value">"firstName"</span><span class="tag">></span>
<span class="tag"><</span><span class="tag-name">br</span>&nbsp;<span class="tag">/></span>
Last Name :
<span class="tag"><</span><span class="tag-name">input</span>&nbsp;<span class="attribute">type</span>=<span class="attribute-value">"text"</span>&nbsp;<span class="attribute">ng-model</span>=<span class="attribute-value">"lastName"</span><span class="tag">></span>
<span class="tag"><</span><span class="tag-name">br</span><span class="tag">></span>
Full Name: {{firstName + " " + lastName }}
<span class="tag"></</span><span class="tag-name">div</span><span class="tag">></span></span>

<span>

62. What is the process of inserting an embedded view from a prepared TemplateRef?

@Component({
    selector: 'app-root',
    template: `
        <ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
    `
})
export class AppComponent implements AfterViewChecked {
    @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
    constructor() { }

    ngAfterViewChecked() {
        this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
    }
}

63. How can you hide an HTML element just by a button click in angular?

An HTML element can be easily hidden using the ng-hide directive in conjunction along with a controller to hide an HTML element on button click.

View

<div ng-controller="MyController">
  <button ng-click="hide()">Hide element</button>
  <p ng-hide="isHide">Hello World!</p>
</div>

Controller

controller: function() {
this.isHide = false;
this.hide = function(){
this.isHide = true; }; }

64. What is the purpose of FormBuilder?

The FormBuilder is a syntactic sugar that speeds up the creation of FormControl, FormGroup, and FormArray objects. It cuts down on the amount of boilerplate code required to create complex forms.
When dealing with several forms, manually creating multiple form control instances can get tedious. The FormBuilder service provides easy-to-use control generation methods.

Follow the steps below to use the FormBuilder service:

  • Import the FormBuilder class to your project.
  • FormBuilder service should be injected.
  • Create the contents of the form.

To import the FormBuilder into your project use the following command in the typescript file:

import { FormBuilder } from '@angular/forms';

65. Write a pictorial diagram of Angular architecture.

 

Angular Tutorial - Edureka

 

66. What is the purpose of an async pipe?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, 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.

How are observables different from promises?

Key differences between observables and promises are

ObservablesPromises

Emit multiple values over a period of time.

Emit a single value at a time.

Are lazy: they’re not executed until we subscribe to them using the subscribe() method.

Are not lazy: execute immediately after creation.

Have subscriptions that are cancellable using the unsubscribe() method, which stops the listener from receiving further values.

Are not cancellable.

Provide the map for forEach, filter, reduce, retry, and retryWhen operators.

Don’t provide any operations.

 

 

Now let’s see code snippets / examples of a few operations defined by observables and promises.

Operations

Observables

Promises

Creation

const obs = new Observable((observer) => {

observer.next(10);

}) ;

const promise = new Promise(() => {

resolve(10);

});

Transform

Obs.pipe(map(value) => value * 2);

promise.then((value) => value * 2);

Subscribe

const sub = obs.subscribe((value) => {

console.log(value)

});

promise.then((value) => {

console.log(value)

});

Unsubscribe

sub.unsubscribe();

Can’t unsubscribe

With this information, we have some idea about what observables and promises are, how they’re initialised.

67. What is ngOnInit? How is it defined?

ngOnInit is a life cycle hook used by Angular to signify that the component has finished being created.
The ngOnInit is defined in the following way:
To use OnInit, we must import it into the component class as follows:

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

It is not necessary to implement OnInit in every component.

How to use ngFor in a tag?

To use ngFor, let’s create a component so that we can have a working HTML template:


@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
<th>Index</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes">
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {

heroes = HEROES;

}

68. What are Angular building blocks?

The main building blocks for Angular are modules, components, templates, metadata, data binding, directives, services, and dependency injection. We will be looking at it in a while. Angular does not have a concept of “scope” or controllers; instead, it uses a hierarchy of components as its main architectural concept.
Components:
We have one or more components at the heart of every Angular App. In fact, in the real world, we create complicated apps that contain tens of components. The data, HTML markup, and logic for a view behind the view are all encapsulated in a Component. Component-based design is embraced by Angular, allowing us to work on smaller, more maintainable portions that may also be reused in different places.
Every application must have at least one component, referred to as the appcomponent or root component. Starting with the appcomponent, a real-world Angular app is effectively a tree of components.
Modules:
A module is a container that holds a collection of connected components. Every angular app contains at least one module, which we refer to as the app module. We may want to divide our modules into smaller, more maintainable modules as our application expands. As the programme expands, we will need to subdivide our app module into smaller modules, each of which will be responsible for a different section. It has components that are connected.

69. List the Differences Between Just-In-Time (JIT) Compilation and Ahead-Of-Time (AOT) Compilation

Angular provides two types of compilation:

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

Just in Time - Angular Interview Questions - Edureka

In JIT compilation, the application compiles inside the browser during runtime. Whereas in the AOT compilation, the application compiles during the build time.

With JIT, the compilation happens during run-time in the browser. It is the default way used by Angular. The commands used for JIT compilation are –

ng build ng serve

In AOT compilation, the compiler compiles the code during the build itself. The CLI command for aot compilation is –

ng build --aot ng server –aot

AOT is more suitable for the production environment whereas JIT is much suited for local development.

70. What do you mean by component test harness in Angular 12?

A component harness is a class that lets a test interact with a component via a supported API. Each harness’s API interacts with a component the same way a user would. By using the harness API, a test insulates itself against updates to the internals of a component, such as changing its DOM structure.
Earlier, With Angular 9 there was this component test harness that provided a readable and robust API base for testing Angular material components with the supported API at test.
With this new version 12, we now have harnesses for all components, so even more test suites can now be built by developers.This comes with a lot of updates, performance improvements and even new APIs. Now the parallel function makes dealing with async actions inside tests easier because you can run multiple async interactions with your components in parallel. A function like the manual change detection will now give you access to even better control of detection by just disabling auto change detections inside your unit tests

 

71. Mention about the speed factor of latest Angular version

The first thing Angular has been consistently doing with new versions is the commitment to optimizing for speed.

Below mentioned are the features that are implemented in the latest version of Angular to enhance the performance and speed:

  • Faster Builds

In this new version, Angular gets even faster than you know, from the dev to even the build cycle. This was possible through a few changes and updates on things like compilation, which now uses TypeScript 4.0 and faster processes like the ngcc update, now up to four times faster.

  • Auto Font Inlining

The first contentful paint of your app is to set up with automatic inlining. This means that as you run ng serve, Angular will now download and inline fonts that are used or linked in your project so that everything loads up even faster. This update comes right out of the box with Angular 12, so update your version now!

Q73.How do you define typings for custom elements? 

// Define an interface for your custom element properties

interface CustomElementProps {

  prop1: string;

  prop2: number;

}

 

// Define the controller for your custom element

class CustomElementController {

  props: CustomElementProps;

 

  constructor() {

    this.props = {} as CustomElementProps;

  }

}

 

// Define the directive for your custom element

function customElementDirective(): angular.IDirective {

  return {

    restrict: ‘E’,

    scope: {},

    bindToController: {

      prop1: ‘@’,

      prop2: ‘<‘

    },

    controller: CustomElementController,

    controllerAs: ‘vm’,

    template: `

      <div>

        <p>{{ vm.props.prop1 }}</p>

        <p>{{ vm.props.prop2 }}</p>

      </div>

    `

  };

}

 

// Register the directive with your AngularJS module

angular.module(‘yourModuleName’, [])

  .directive(‘customElement’, customElementDirective);

 

Q74.Give an example for attribute directives?

Here’s an example of an attribute directive in Angular:

import { Directive, ElementRef, HostListener } from ‘@angular/core’;

@Directive({

  selector: ‘[appHighlight]’

})

export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @HostListener(‘mouseenter’) onMouseEnter() {

    this.highlight(‘yellow’);

  }

  @HostListener(‘mouseleave’) onMouseLeave() {

    this.highlight(null);

  }

  private highlight(color: string | null) {

    this.el.nativeElement.style.backgroundColor = color;

  }

}

In this example:

  • We create an attribute directive called HighlightDirective using the @Directive decorator.
  • The directive’s selector is [appHighlight], which means it can be used as an attribute in HTML like <div appHighlight>…</div>.
  • We inject ElementRef to access the DOM element the directive is applied to.
  • We use @HostListener decorators to listen for mouse enter and mouse leave events on the host element (the element the directive is applied to).
  • When the mouse enters the element, onMouseEnter is called, which in turn calls highlight(‘yellow’) to change the background color to yellow.
  • When the mouse leaves the element, onMouseLeave is called, which calls highlight(null) to remove the background color.

Q75. How do you define routes?

Here’s how you would define routes in Angular using the @angular/router module without the explanations:

// Import necessary modules

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

import { HomeComponent } from ‘./home.component’;

import { AboutComponent } from ‘./about.component’;

import { ContactComponent } from ‘./contact.component’;

// Define routes

const routes: Routes = [

  { path: ”, component: HomeComponent },

  { path: ‘about’, component: AboutComponent },

  { path: ‘contact’, component: ContactComponent },

  { path: ‘**’, redirectTo: ” } // Redirect to home if route not found

];

// Export RouterModule with configured routes

export const AppRoutingModule = RouterModule.forRoot(routes);

Make sure to have HomeComponent, AboutComponent, and ContactComponent defined and imported correctly.

Q76..Give an example of few metadata errors?

Here are a few examples of metadata errors that can occur in Angular:

1.Missing Metadata Error:

@Component({

  selector: ‘app-example’,

  templateUrl: ‘./example.component.html’,

  // Missing ‘providers’ metadata

})

export class ExampleComponent { }

2.Unknown Metadata Property Error:

@Component({

  selector: ‘app-example’,

  templateUrl: ‘./example.component.html’,

  // Incorrect metadata property ‘template’ instead of ‘templateUrl’

  template: ‘<h1>Example</h1>’

})

export class ExampleComponent { }

3.Duplicate Metadata Error:

@Component({

selector: ‘app-example’,

templateUrl: ‘./example.component.html’,

// Duplicate ‘selector’ metadata

selector: ‘app-example’

})

export class ExampleComponent { }

4.Invalid Metadata Value Error:

@Component({

  selector: ‘app-example’,

  templateUrl: ‘./example.component.html’,

  // Invalid value for ‘changeDetection’

  changeDetection: ‘auto’

})

export class ExampleComponent { }

Q77. How do you specify angular template compiler options?

import { CompilerOptions } from ‘@angular/core’;

 

const compilerOptions: CompilerOptions = {

  preserveWhitespaces: false,

  strictInjectionParameters: true,

  strictTemplates: true,

  enableIvy: true

};

 

@NgModule({

  // Other module configurations…

  providers: [

    { provide: COMPILER_OPTIONS, useValue: compilerOptions, multi: true }

  ]

})

export class AppModule { }

So this brings us to the end of the Angular interview questions article. The topics that you learned in this Angular Interview Questions article are the most sought-after skill sets that recruiters look for in an Angular Professional. These set of Angular Interview Questions will definitely help you ace your job interview. Good luck with your interview!

Learn more about Questions

How to make FileReader work with Angular

How to Check Empty Object in Angular

How to load external scripts in angular

 

Know about What are the Advantages and Disadvantages of Angular? and learn about Angular tutorial

Take your mobile app development skills to the next level with a Flutter Certification.

Got a question for us? Please mention it in the comments section of this Angular Interview Questions and we will get back to you.

Upcoming Batches For Angular Certification Training Course Online
Course NameDateDetails
Angular Certification Training Course Online

Class Starts on 15th February,2025

15th February

SAT&SUN (Weekend Batch)
View Details
Comments
10 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

70+ Angular Interview Questions for Freshers and Experienced

edureka.co