Top 80+ AngularJS Interview Question and Answer 2024

Interview Question and Answer
Table of contents
  1. What is AngularJS?

The AngularJS framework is a JavaScript framework for creating rich and extensible web applications.

It runs on plain JavaScript and HTML, so it doesn’t require any additional dependencies. Single Page Applications are ideal for AngularJS (SPA). It’s primarily used to link JavaScript objects to HTML user interface elements.

  1. How do you share data between controllers?

Create an AngularJS server that will store and inject the data into the controllers.

The cleanest, quickest, and simplest way to assess is to use a service. However, there are a few other options for data sharing between controllers, such as: – Making use of occasions – Getting direct access to the controllers by using $parent, nextSibling, controllerAs, and so on. – Adding the data to the $rootScope (not a good practice) All of the methods mentioned above are right, but they are not the most effective or simple to test. On egghead.io, there is a strong video description.

  1. What is the difference between ng-show/ng-hide and ng-if directives?

If the specified condition is not met, ng-if does not render the portion of the DOM element with which it is connected, while ng-show renders the DOM element but sets its CSS property of display to zero if the specified condition is not met.

  1. How are the $ and $$ prefixes in AngularJS used?

In AngularJS, the $$ variable is used as a private variable to avoid unintended code collisions with user code.

The $ prefix, on the other hand, may be used to denote angular core functionality (like a variable, parameter, property or method).

Check out angularjs courses for free.

  1. Where should we implement the DOM manipulation in AngularJS?

In the directives. DOM Manipulation can only be done in directives, not in controllers, utilities, or anywhere else.

  1. Is it a good or bad practice to use AngularJS together with jQuery?

It is definitely a bad practice. We should avoid using jQuery and instead try to implement the solution using AngularJS. When it comes to manipulating the DOM, jQuery takes a conventional imperative approach, which means the programmer must articulate the individual steps leading up to the desired outcome.

AngularJS, on the other hand, uses declarative DOM manipulation. Instead of thinking about all of the nuances of how to achieve the desired result, we simply declare what we want, and AngularJS takes care of the rest.

  1. If you were to migrate from Angular 1.4 to 1.5, what is the main thing that would need refactoring?

Changing to the latest Angular 1.5 components, change .directive to .component.

  1. How would you specify that a scope variable should have one-time binding only?

Using the prefix “::” in front of it. This helps you to see if the candidate is familiar with the AngularJS variable bindings.

  1. How do we make HTTP get and post calls in Angular?

To make HTTP calls, we must use Angular’s “$http” service. To use the http services, you must use “$http” as an input in your function parameters, as shown in the code below.

<!-- wp:paragraph -->
<p>function CustomerController($scope,$http)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>$scope.Add = function()</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$http({ method: "GET", url: "http://localhost:8438/SomeMethod" &nbsp; &nbsp; }).success(function (data, status, headers, config)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;// Here goes code after success</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

At least three things are needed by the “$http” service API:-

  • First, let’s define the terms “POST” and “GET.”
  • Second, the URL of the resource where the operation can take place.
  • Finally, we must describe the “performance” function, which will be called when we receive an answer from the server.

$http({ method: “GET”, url: “http://localhost:8438/SomeMethod”    }).success(function (data, status, headers, config)

{

// Here goes code after success

}

  1. In Angular, what are services?

Dependency injection is made easier with the aid of a service. Let’s assume we have the “Customer” class, which requires the “Logger” object. The “Logger” object may now be of the “FileLogger” or “EventLogger” types.

function Customer($scope,$http, Logger)

{

        $scope.Logger = Logger;

}

As a result, you can use the application’s “support” method to link the “EventLogger” object to the “Logger” input parameter of the “Customer” class.

var app = angular.module(“myApp”, []); // creating a APP

app.controller(“Customer”, Customer); // Registering the VM

app.service(“Logger”, EventLogger); // Injects a global Event logger object

As a consequence, when the controller object is generated, the “EventLogger” object is injected into the controller class automatically.

  1. What is the difference between Factory and Service?

In angular, “Factory” and “Service” are two different ways to do DI (Dependency injection). Please read the preceding question to learn more about DI.

As a consequence, when we use “support” to describe DI, as shown in the code below. This generates a new GLOBAL instance of the “Logger” entity, which is then inserted into the feature.

app.service(“Logger”, Logger); // Injects a global object

When you use a “factory” to define DI, no instance is made. It simply transfers the method to the user, who must then make internal calls to the factory for object instances.

app.factory(“Customerfactory”, CreateCustomer);

The image below illustrates how the DI method for “Service” varies from that for “Factory.”

Factory:

Usage:

When we need to build various types of objects based on different scenarios. Depending on the situation, we might want to construct a simple “Customer” object, a “Customer” with “Address” object, or a “Customer” with “Phone” object. For a more in-depth interpretation, see the previous question.

Instance:

There was no instance made. A reference to a method is transmitted.

Service:

Usage:

When we need to inject utility or shared functions like Utility, Logger, Error Handler, and so on.

Instance:

A shared and global instance is developed.

  1. How do I check whether a field is correct for errors?

You may use the DOM code below to search for a particular sector.

!frm1.CustomerName.$valid

  1. What does it mean to have an SPA (single page application)?

SPA is a concept in which, instead of loading pages from the server through postbacks, we build a single shell page or master page and load the webpages inside it.

  1. What are the Benefits of Angularjs SPAs (Single Page Applications) and Why Develop an SPA with Angularjs?
  • The user experience has been improved.
  • Since less bandwidth is used, web pages refresh faster.
  • The framework – index.html, CSS bundle, and javascript bundle – is now easier to deploy in development.
  • To split the bundles into multiple bits, code splitting can be used.

Here are a few reasons why AngularJS is the obvious winner:

1) No Dependencies

Backbone.js, unlike AngularJS, relies on underscore.js and jQuery. ember JS, on the other hand, is reliant on handlebars and jQuery.

2) Routing

When compared to other javascript frameworks, navigation between web pages created with AngularJS is extremely easy. Because the directives in AngularJS are lightweight, the performance metrics of the framework are impressive.

3) Testing

After the framework is developed with AngularJS, selenium can be used to perform automated testing for quality assurance. This is one of the most impressive features of AngularJS-based applications.

4) Data Binding

Since AngularJS follows the MVC architecture, it supports two-way data linking, which means that if the model is modified, the view is updated as well.

As a result, the user will display the data according to his preferences.

5) Support for the Browser

Most browsers, like Internet Explorer 9 and higher, support AngularJS. It can also be used on cell phones, tablets, and laptops.

6) Agility

AngularJS is agile, which means it can respond to new demands from companies as they emerge in dynamic work environments. To service these requests, controllers can be implemented in an MVC architecture.

In AngularJS, there are approximately 30000 modules that are readily available for rapid application growth. When a developer wants to customise an existing programme, he can use pre-built modules and change the code rather than creating the whole application from scratch.

Furthermore, since there are so many contributors and experts in AngularJS, you can receive prompt answers to any questions you post on discussion forums.

  1. In Angular, how do we render a custom directive?

We’ve only looked at predefined Angular directives so far, such as “ng-controller,” “ng-model,” and so on. But what if we want to make our own Angular directive and apply it to HTML elements as in the code below?

We must use the “directive” function to register a custom directive with an Angular application in order to generate one. We must define the feature that will provide the rationale for that directive when calling the “register” form of “directive.”

For example, we’ve generated a copy right directive in the code below, which returns a copy right text.

<!-- wp:paragraph -->
<p>app.directive('companyCopyRight', function ()</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>return</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>{</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;template: '@CopyRight questpond.com '</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;};</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>});</p>
<!-- /wp:paragraph -->

The above custom directive can be later used in elements as shown in below code.

<div ng-controller=”CustomerViewModel”>

<div company-copy-right></div>

</div>

  1. What are the various forms of custom directives in AngularJS?

Angular directives come in a variety of types, depending on how restrictive you want your custom directive to be.

To put it another way, do you want your custom directive to be applied only to HTML elements, only to attributes, only to CSS, and so on?

There are four different types of custom directives in total:-

  • Element directives (E)
  • Attribute directives (A)
  • CSS class directives (C)
  • Comment directives (M)

A basic custom directive implementation at the element level is shown below.

myapp.directive(‘userinfo’, function()

{

    var directive = {};

    directive.restrict = ‘E’;

    directive.template = “User : {{user.firstName}} {{user.lastName}}”;

    return directie;

});

This directive can only be used at the element level because the “restrict” property is set to “E,” as seen in the code snippet below.

<userinfo></userinfo>

It will not work if you try to use it at the attribute level, as seen in the code below.

<div userinfo></div>

So, “E” stands for feature, “A” stands for attribute, “C” stands for CSS, and “M” stands for comments.

  1. Define the terms “sessionStorage,” “cookies,” and “localStorage.”

The following are the distinctions:

SessionStorage – The data for a specific session is saved. The information would be lost if the browser tab is closed or if a session is ended. The maximum size that can be processed is 5MB.

LocalStorage – No expiration date is set for the data. JavaScript or clearing the browser cache are the only ways to clear the details. The capacity cap is higher than sessionStorage and cookie storage limits.

Cookies – It saves information that must be sent back to the server in response to such requests. The cookie’s expiration depends on the form and length of the cookie, which can be set on either the server-side or the client-side. The maximum size that can be saved is 4KB.

  1. Is it possible to apply an Angular directive template to an HTML page?

Yes, you can set the template to the page directly using the directive’s “templateUrl” property, as seen in the code snippet below.

directive.templateUrl = “/templates/footer.html”;

  1. What are the differences between switchMap, concatMap, and mergeMap?

Reply:

switch map: When a new mapped observable arrives, the switch map will unsubscribe from the previous one.

concatMap: Queuing each new Observable and then subscribing to a new Observable until the previous one has ended.

mergeMap: instead of doing something, we simply keep subscribing to any new observable that the map returns.

  1. How do you differentiate between scan() and reduce()?

Scan: sequentially apply a function to each object emitted by an Observable, and emit each value.

Reduce: sequentially apply a function to each object emitted by an Observable and emit the final value

  1. What is the meaning of a pure pipe?

When Angular senses a shift in the value or parameters passed to a pipe, it calls a pure pipe.

  1. What is the meaning of an async pipe?

The async pipe subscribes to an Observable or Promise and returns its most recent value.

The async pipe labels the part to be tested for changes when a new value is emitted.

To prevent memory leaks, the async pipe unsubscribes automatically when the variable is killed.

  1. In AngularJS, what are filters?

The primary function of filters is to adjust data so that it can be combined into an expression or directive using the pipe character (it is used for applying filters in an angular symbol of a pipe that is (|) or this is the symbol).

The value of an expression is formatted by a filter for presentation to the user. We can use them in view models, controllers, and utilities, and we can easily generate our own filter. AngularJS provides a module called a filter. A filter has nine components that it provides.

Currency, date, filter, JSON, limitTo, and so on are some examples.

  1. How does an async pipe hold memory leaks at bay?

When a part is deleted, the async pipe automatically unsubscribes to prevent memory leaks.

  1. What does it mean to be a component?

In Angular, a component is a class that is used to create building blocks.

  1. What is the difference between a component and a directive?

Components have their own HTML and Style(View), whereas a directive is simply a behaviour that extends the component’s elements.

  1. What is the mechanism by which components interact with one another?

Components for three-way communication:

Passing the state of one variable to another

Passing value from a parent variable to a service

  1.  In Angular, how do you establish two-way data binding?

The ngModel directive incorporates the input and output binding into a single notation.

Eg: <input [(ngModel)]=”name” >  {{name}}

  1. In AngularJS, how many different types of data bindings are there?

Both one-way and two-way binding are supported by AngularJS.

If we modify the data model in one way binding, there will be no dynamic change in the view, but in two way binding, there will be a dynamic change whenever the data model is changed.

  1. How would you go about making a component that displays error messages all over your app?

Set the error message to an angular variable, then check to see whether that variable exists to see whether value or Error should be shown.

  1. What does a lean component mean to you?

We use the lean component solely to display data.

  1. What is the best way to send a form?

ngSubmit ()

  1. What are the differences between NgForm, FormGroup, and FormControl? How should they collaborate?

ngForm:- ngForm:- ngForm:- NgForm automatically connects to the tags when we import the Form module, and it always operates from behind.

  1. What are the benefits of using FormBuilder?

FormBuilder speeds up the development of FormControl, FormGroup, and FormArray instances. It cuts down on the amount of boilerplate code required to create complex types.

  1. What is the scope of the AngularJs Global API?

It is a set of global JavaScript functions that are used to perform tasks such as object comparison, iteration, and data conversion.

There are a few standard API functions, such as:

  • angular. lowercase:It transforms a string from uppercase to lowercase.
  • angular. uppercase:It transforms a string from lowercase to uppercase.
  • angular. isString:If the current reference is a string, it will return true.
  • angular. isNumber:If the current reference is a number, it will return valid.
  1. Distinction between AngularJS and React.JS.

Angularjs:

Google launched AngularJS, a TypeScript-based JS platform, in October 2010. It is an open source and fully free platform that is used in SPA projects (i.e. Single Page Application projects).

Reactjs:

Facebook released React.JS in March 2013 as a javascript library for creating user interfaces. React components can be used on several websites, but not as a single-page application (i.e. Single Page Application).

  1. What is the purpose of a router?

When we need the path to an element, we’ll use the router

Syntax:

this.router.navigate ([‘/ component name']);
  1. What command is used to render a service and an angle service?

It assists us in repeating the code. You can reuse code from various components when building a service. The gg service user command is used to build a service in the angle (created a user service when using this command).

  1. What is the angle of the reliability injection?

When a feature is dependent on another, the function is enabled or disabled when the functionality is enabled.

  1. What is a Router Outlet, and what does it do?

Router Outlet is a method for grouping elements that replaces templates. To put it another way, represent or include elements in a template at a particular location.

  1.  Explain the string interpolation technique.

The parentheses package represent data from a variable when used with the HTML tag. For instance, an HTML page containing variableName, where variableName refers to the value in the templatecript (component) chart; HTML. String interpolation is the term for this whole concept.

  1.  What are the different methods for data binding?

HTML (template) and typescript data are linked together (component) There are three ways to collect data:

  • property bonding
  • event binding
  • two way data binding.
  1. What exactly is a ngModel, and how do we portray it?

In the text field, ngModel is a directive. These data bindings are two-way. ngModel[[]]

  1. What constitutes a chain 4 appointment?

This is a algorithm. Any time a subscription method is called, a separate execution is run.

  1. What exactly are pipes?

This function is used to modify the template’s output; the string is resized and displayed in the template. This can result in a shift in the date format.

  1. Distinction between ng-class and ng-style.

CSS class loading is possible in Ng-class, while CSS style can be set in ng-style.

  1. What are the benefits of hiring a decorative designer?

Decorators are people who make things look good. Designers are planned for a future version of JavaScript, but they are already in use by the angle community and are part of the TitzScript kit. Ornamental designers are enabled by a highlighted @ symbol, and a class, parameter, pattern, or property is generated.

  1. What are angled models, and how do you use them?

Templates in AngularJS are written in HTML and include AngularJS-based elements and attributes. The model and controller details are combined in an AngularJS template to create a dynamic display that can be viewed in a browser.

  1.  Do I need Jquery for Angular?

No, Angular does not need Jquery. It’s not based on Jquery.

  1.  What is the difference between one-way binding and two-way binding?

– One-way binding means that the scope variable in the html will be set to the model’s first value (i.e. assigned to)

– Two-way binding means that the value of the scope variable changes when its model is assigned to a different value.

51. Explain how $scope.$apply() works?

It will re-evaluate all declared ng-models and apply the update to those that have changed (i.e. assigned to a new value)

Why? $scope.$apply() is a key angular feature that can never be used explicitly; it causes the angular engine to operate on all watched variables and external variables and apply changes to their values.

Source: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

52. What directive would you use to hide elements from the HTML DOM by removing them from that DOM not changing their styling?

When the ngIf Directive is applied to an element, if the condition is incorrect, the element is removed from the DOM.

53. What makes the angular.copy() method so powerful?

It duplicates the variable in a deep way.

A deep copy of a variable is one that does not share the same memory address as the original variable. When you assign one variable to another, you’re usually creating a “shallow copy,” which means the two variables are pointing to the same memory location. As a result, if we change one, we must also change the other.

Sources: – https://docs.angularjs.org/api/ng/function/angular.copy – https://en.wikipedia.org/wiki/Object_copying

54. How can you execute a promise return in an Angular service? Write a code snippet as an example?

To add promise functionality to a service, we first inject the “$q” dependency and then use it as follows:

<!-- wp:paragraph -->
<p>angular.factory('testService', function($q){</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>return {</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>getName: function(){</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>var deferred = $q.defer();</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>//API call here that returns data</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>testAPI.getName().then(function(name){</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>deferred.resolve(name)</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>})</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>return deferred.promise;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;})</p>
<!-- /wp:paragraph -->

The $q library is a helper provider for asynchronous functionality that implements promises and deferred items.

Source: https://docs.angularjs.org/api/ng/service/$q

55. What are the functions of services in AngularJS, and what services are provided by default?

AngularJS Services are artefacts that give an AngularJS app separation of concerns. – A factory method or a service method may be used to build AngularJS services. – Services are one-of-a-kind components. A single instance of the service would be used by all components of the application (into which the service is injected). – An AngularJS service allows business logic to be developed independently of the View logic that will be used for it.

AngularJS has the following built-in services: – service $http: The $http service is a key Angular service that allows you to communicate with remote HTTP servers using the XMLHttpRequest object in your browser or JSONP. – $log is a service that allows you to keep track of what’s happening in your Logging is a simple service. The default implementation writes the message to the browser’s console safely – the $anchorScroll: it scrolls to the element associated with the specified hash or (if omitted) the current value of $location.hash () You may be wondering why someone needs to know about AngularJS Services. Understanding the purpose of AngularJS Services, on the other hand, increases the versatility of AngularJS code. Using services is the easiest way to build a reusable API in Angular. Using services in an AngularJS app is the easiest way to build a reusable API.

Overview:

AngularJS Services aid in the creation of reusable components. The factory() method or the service() method may also be used to build a Service. An AngularJS Controller or another service can be injected with a standard service.

Source: – https://docs.angularjs.org/guide/services – http://www.tutorialspoint.com/angularjs/angularjs_services.htm

56. When you create a directive, you can use it in a variety of ways in the view. Do you know how to use a directive in various ways? How do you specify how your order will be implemented?

A directive may be used as an attribute, feature, or class name when it is created. Set the restrict choice in your directive declaration to specify which method to use.

Usually, the restrict option is set to:

‘A’ matches only attribute names; ‘E’ matches only entity names. ‘C’ – just fits the name of the class.

All of these constraints can be combined as needed:

‘AEC’ – matches the name of an attribute, feature, or class.

Please refer to the AngularJS documentation for more details.

57. When should you use an attribute Vs an element?

When building a part that is in charge of the template, use an element. When you’re adding new features to an existing feature, use an attribute.

This topic is important so that developers can understand the various ways a directive can be used within a view, as well as when to use each method.

Sources: https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object

58. How do you reset a $timeout, $interval(), and disable a $watch()?

To reset a timeout and/or $interval, first assign the function’s result to a variable, then use the.cancel() function.

var customTimeout = $timeout(function () {

// arbitrary code

}, 55);

$timeout.cancel(customTimeout); 

We use the deregistration feature to turn off $watch(). After that, $watch() returns a deregistration feature, which we save in a variable and call when it’s time to clean up.

var deregisterWatchFn = $scope.$on(‘$destroy’, function () {

// To disable the watch, we use the deregistration function. 

    deregisterWatchFn();

});

59. Explain what is a $scope in AngularJS is?

The application model is referenced by the scope object. It’s an expression execution sense. Scopes are organised in a hierarchical system that mirrors the application’s DOM structure. Expressions can be monitored and events can be propagated using scopes. The model is represented by scopes, which are objects that refer to it. They serve as a connection between the controller and the view.

This question is relevant because it assesses a person’s understanding of the $scope object, which is one of the most important concepts in AngularJS. Scope serves as a connection between the view and the model.

Source: https://docs.angularjs.org/guide/scope

60. What are Directives?

Directives are DOM element markers (such as an attribute, element name, comment, or CSS class) that tell AngularJS’ HTML compiler ($compile) to apply a particular behaviour to the DOM element (e.g. through event listeners) or even transform the DOM element and its children. Angular includes a number of these directives, such as ngBind, ngModel, and ngClass. You can create your own directives for Angular in the same way as you can create controllers and services. The HTML compiler traverses the DOM when Angular bootstraps your programme, matching directives against DOM elements.

This is very important question since directives describe the UI of a single-page app. You must understand how to construct a new custom directive or use one that has already been built into AngularJS.

61. What is DDO Directive Difinition Object?

DDO is an entity that is used to create custom directives. The parameters of a regular DDO object are as follows.

var directiveDefinitionObject = {

priority: 0,

  template: ‘<div></div>’, // or // function(tElement, tAttrs) { … },

// or

// templateUrl: ‘directive.html’, // or // function(tElement, tAttrs) { … },

transclude: false,

restrict: ‘A’,

templateNamespace: ‘html’,

scope: false,

  controller: function($scope, $element, $attrs, $transclude, otherInjectables) { … },

  controllerAs: ‘stringIdentifier’,

  bindToController: false,

  require: ‘siblingDirectiveName’, // or // [‘^parentDirectiveName’, ‘?optionalDirectiveName’, ‘?

  ^optionalParent’],

  compile: function compile(tElement, tAttrs, transclude) {

  return {

    pre: function preLink(scope, iElement, iAttrs, controller) { … },

         post: function postLink(scope, iElement, iAttrs, controller) { … }

       }

   // or

  // return function postLink( … ) { … }

},

// or

// link: {

//  pre: function preLink(scope, iElement, iAttrs, controller) { … },

//  post: function postLink(scope, iElement, iAttrs, controller) { … }

// }

// or

// link: function postLink( … ) { … }

  };”

This question primarily assesses whether the applicant is familiar with writing custom directives.

Read more at https://docs.angularjs.org/guide/directive

62. What is a singleton pattern and where we can find it in AngularJS?

Is a great pattern that prevents a class from being used more than once. In Angular, the singleton pattern can be used in dependency injection and services.

In a sense, if you call new Object() twice without using this pattern, you’ll be allocating two pieces of memory for the same object. If an object already exists, the singleton pattern allows you to reuse it.

Source: http://joelhooks.com/blog/2013/05/01/when-is-a-singleton-not-a-singleton/

63. What is an interceptor?

Is an excellent pattern that prevents a class from being used several times. The singleton pattern can be used in both dependency injection and services in Angular.

In a sense, if you call new Object() twice without this pattern, you are allocating two pieces of memory for the same object. If an object exists, you reuse it with the singleton pattern.

64. What are common uses of an interceptor in AngularJS?

Requests and responses are the two forms of requests that pass through the interceptor (with requestError and responseError respectively). This code can be used to manage bugs, authentication, or middleware in all requests and responses.

Source: https://docs.angularjs.org/api/ng/service/$http

65. How would you programmatically change or adapt the template of a directive before it is executed and transformed?

The compilation feature will be used. Before transclusion and template transformation, the compile feature gives you access to the directive’s template, enabling you to make adjustments to DOM elements safely. This is particularly useful in situations where the DOM must be built using runtime directive parameters.

Source: https://docs.angularjs.org/api/ng/service/$compile

66. How would you validate a text input field for a twitter username, including the @ symbol?

To perform a regex match that matches Twitter usernames, you’d use the ngPattern directive. Validating phone numbers, serial numbers, barcodes, zip codes, and all other text input follows the same idea. Note that when the plain pattern attribute is used, this directive is also applied, with two exceptions: ngPattern does not set the pattern attribute, so HTML5 constraint validation is not available. The pattern value must be interpolated, and the ngPattern attribute must be an expression.

<script>

 angular.module(‘ngPatternExample’, [])

.controller(‘ExampleController’, [‘$scope’, function($scope) {

  $scope.regex = ‘\\d+’;

 }]);

</script>

<div ng-controller=”ExampleController”>

 <form name=”form”>

 <label for=”regex”>Set a pattern (regex string): </label>

 <input type=”text” ng-model=”regex” id=”regex” />

 <br>

<label for=”input”>This input is restricted by the current pattern: </label>

<input type=”text” ng-model=”model” id=”input” name=”input” ng-pattern=”regex” /><br>

<hr>

input valid? = <code>{{form.input.$valid}}</code><br>

 model = <code>{{model}}</code>

</form>

</div>

Source:https://docs.angularjs.org/api/ng/directive/ngPattern

67. How would you implement application-wide exception handling in your Angular app?

$exceptionHandler is an Angular built-in error handler that can be easily overridden, as seen below:

<!-- wp:paragraph -->
<p>myApp.factory('$exceptionHandler', function($log, ErrorService) {</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>return function(exception, cause) {</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;&nbsp;&nbsp; if (console) {</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; $log.error(exception);</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; $log.error(cause);</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp; &nbsp; }</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&nbsp;&nbsp; &nbsp; ErrorService.send(exception, cause);</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>};</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>});</p>
<!-- /wp:paragraph -->

This is particularly useful for submitting errors to third-party error logging services or helpdesk software. Event callback errors are not propagated to this handler, but they can be manually relayed to it by calling $exceptionHandler(e) from within a try-catch block.

68. How do you hide an HTML element via a button click in AngularJS?

We can hide an HTML element on button click by using the ng-hide directive in conjunction with a controller.

<!-- wp:paragraph -->
<p>&lt;div ng-controller="MyCtrl"&gt;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&lt;button ng-click="hide()"&gt;Hide element&lt;/button&gt;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&lt;p ng-hide="isHide"&gt;Hello World!&lt;/p&gt;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>&lt;/div&gt;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>function MyCtrl($scope){</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>$scope.isHide = false;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>$scope.hide = function(){</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>$scope.isHide = true;</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>}</p>
<!-- /wp:paragraph -->

69. How would you react to model changes to trigger some further action? For instance, say you have an input text field called email and you want to trigger or execute some code as soon as a user starts to type in their email.

The $watch feature in our controller can be used to accomplish this.

function MyCtrl($scope) {

$scope.email = “”;

$scope.$watch(“email”, function(newValue, oldValue) {

if ($scope.email.length > 0) {

console.log(“User has started writing into email”);

}

});

}

70. How do you disable a button depending on a checkbox’s state?

The ng-disabled directive can be used to bind the checkbox’s state to its condition.

<body ng-app>

<label><input type=”checkbox” ng-model=”checked”/>Disable Button</label>

<button ng-disabled=”checked”>Select me</button>

</body>

71. In angular, what does the calls to the HTTP methods return ?

Calls to HTTP methods in Angular return an observable rather than a commitment. An observable can be thought of as a stream of events that provide values to everyone who has subscribed to it.

72. Is it possible to use an AngularJS commandline to create a part from the terminal?

The ngFor generator in Angular allows us to generate components from the terminal. If I want to create a contact component, I simply run ng generate component contact, and it will generate all of the required files for me. All I have to do now is update it to use it!

73. An operator that we can use to avoid any 404 error is?

We should use? in Angular. to stop any unnecessarily erroneous file not found errors. Let’s assume we have contact details but didn’t provide a picture URL, but instead used [src]=contact? Even if a picture has not been inserted, the photo URL will return 404.

74. Which method is used to listen for an emitted response while using the Angular HTTP module to make a request?

In the Angular Http module, use the method to listen for an emitted response to make a request.

75. What is the Router directive that can be placed on elements to navigate to a new route?

[routerLink] is a router command that can be used on elements to navigate to a new path.

76. Which property is used to retrieve the form values if “form” is a NgForm object?

[form.value] can be used to get the form value.

77. Is there an Angular class that can be used to construct an instance that will be passed as an argument to the HTTP request method?

[Request].

78. Is there an Angular generator for creating api.service.spec.ts inside the shared component? 

[ng generat service shared/api].

79. A JSON Web Token consists of …. ?

JSON Web Token consists of header, payload and signature.

80. A secret named should be used to sign a JWT.

Password with high protection. It’s not easy to come up with long, high-quality random passwords. You can easily make one by going to https://www.grc.com/passwords.htm.

81. What is the format of the Authorization header if you have a JWT token?

The authorization header should be Bearer [token].

82. Is it possible to use MVC in AngularJS?

YES

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top