11/Jan/2024 | 20 minutes to read
js
Here is a List of essential Angular Interview Questions and Answers for Freshers and mid level of Experienced Professionals. All answers for these Angular questions are explained in a simple and easiest way. These basic, advanced and latest Angular questions will help you to clear your next Job interview.
These Angular interview questions are targeted for Angular 12, Angular 11, Angular 10, Angular 9, Angular 8, Angular 7 and all versions greater than Angular 2. You must know the answer of these frequently asked Angular interview questions to clear the interview. These Angular questions will help Full Stack developers, Java Developers, .Net Developers, UI or Front End developers and many more to clear the interview.
1. What is Angular?
Angular is an application design framework and a development platform to build sophisticated and efficient single page applications. This document applies to angular version 2.0 and later versions such as Angular 11, Angular 10, Angular 9, Angular 8, Angular 7 etc. For 1.x versions of angular we use the name as AngularJS.
2. What is the latest version of Angular?
You can check Angular version any time on this link Angular Latest Version
2. What is the template type checking in Angular?
3. How is Angular different from AngularJs?
Angular and AngularJS both are the open source JavaScript based frameworks used to develop web based single page applications (SPAs). For angular versions 1.x we gave the name AngularJS and for angular version 2.0 and later we just call it Angular. There are a lot of differences between Angular and AngularJS as below.
4. What are the advantages of using Angular over AngularJS?
Angular is a typescript based free and open-source application design framework and platform for developers which comes with many advantages.
5. What are the main building blocks of an Angular Application?
Angular Architecture provides some basic concepts or main building blocks to develop an application. These main building blocks are:
@NgModule
decorator with some properties. Module can contain any components, service providers and other code for that module.
@NgModule({
imports: [],
declarations: [],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
@Component()
treats
the class just below it as a component class and provides the information for the template and other meta-data information. Example is below.
@Component({
selector: 'web-portal-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
})
export class HomeComponent {
}
@Injectable()
defines the class just below it as a service that can be injected
as a dependency.
@Injectable()
export class UserService {
}
constructor(private service: UserService) { }
7. Explain the Standalone components in Angular?
Standalone components help you to build the applications in a simpler way by avoiding the use of NgModule(s). When you declare a
component as standalone to 'true' it does not need to be declared in NgModule. You can reference the other standalone component, directive
and pipe inside the import array of a standalone component without registering it in NgModule.
For more visit Standalone components.
7. How will you open the browser automatically when running your Angular application?
You can pass the "--open (or just -o)" with the "ng serve" command to automatically open the app in the browser.
ng serve --open
6. What is the difference between NgModules and JavaScript modules?
NgModules are different from JavaScript modules in the following ways.
7. What is the host view in Angular?
When a component is created it's directly associated with a single view that is called host view. The host view plays a critical role during the change detection in Angular. Whenever a component class finds any changes, Angular applies these change detection on the host view first then it checks for child views. It makes sure that any modifications to the component are always reflected in the host view.
8. What are the directives? How many types of directives are available in Angular?
Directives provide the Program logic and extend the power of HTML by providing new syntax.
Angular supports 3 types of directives as below.
{{user.name}}
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[highlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
// directive usage
High light content!
9. What is Data Binding in Angular? Explain 2 way data binding.
Data binding is the way to share the data between a component class and its associated template called view. Angular provides 2 way data binding means component properties can be used in view for data and if you make any changes in view then changes should reflect back in component's properties.
10. What is Interpolation and Template Expressions in Angular?
Interpolation provides the easiest way to bind a component property in the view. In Interpolation you put the property in the double curly braces '{{property=name}}'.
A Template expression is used in double curly braces and produces a value like {{1+1}}, it will produce a value 2. In Property binding an expression is the right side part of
'=' operator.
11. What are the different types of binding available?
Angular provides different ways of binding as below.
Special class
12. What are the lifecycle hooks in angular?
13. How will you share the data between components?
In many scenarios you need to share the data between the components. it can be parent to child, child to parent and unrelated components. So let's understand this with the help of an example.
// parent component
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
parentMessage = "message from parent"
constructor() { }
}
// child component
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `Say {{ childMessage }}`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() { }
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `Message: {{message}} `,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
constructor() { }
message:string;
receiveMessage($event) {
this.message = $event
}
}
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ` `,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hello Testing!"
@Output() messageEvent = new EventEmitter();
constructor() { }
sendMessage() {this.messageEvent.emit(this.message) }
}
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from "../child/child.component";
@Component({
selector: 'app-parent',
template: `
Message: {{ message }}
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child;
constructor() { }
message:string;
ngAfterViewInit() {this.message = this.child.message}
}
@Component({
selector: 'app-child',
template: ``,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message = 'Hello Testing!';
constructor() { }
}
14. What are the Pipes in Angular?
A Pipe provides the functionality of transforming the data from your data input to desired output. For example, You receive some lower case data from the back end and now you
want to display that data as upper case then you can Angular built in pipe 'uppercase'. You can also create your custom pipes in angular.
To implement a custom pipe, decorate your class with '@Pipe' metadata and implement PipeTransform interface's transform method as below.
@Pipe({name: 'exponentialStrength'})
export class ExponentialPipe implements PipeTransform {
transform(value: number, exponent?: number): number {
return Math.pow(value, isNaN(exponent) ? 1 : exponent);
}
}
15. Explain the AOT compilation? Or What is the difference between JIT and AOT?
16. What are the Services in Angular?
In Angular services are the classes with well defined purpose. Services provide the functionality in a modular way which can be reused across the components. To share the data between components you can use services. You can make your components efficient by delegating some functionality code to services like fetch the data from server, validation rules etc. By defining this code into services you can make your code reusable to any component. You can create a service by using @Injectable decorator.
// It's a self registering service, now no need to put this service in providers array in module or component
@Injectable({
providedIn: 'root', // to inject the dependency in root.
})
export class UserService {
}
// You register a service at module level by setting the 'providers' property of @NgModule decorator.
@NgModule({
providers: [
UserService
],
...
})
// You can also register a service at component level by settings 'providers' property of @Component decorator.
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
providers: [ UserService ]
})
17. How to make a service a singleton in Angular?
There are two ways to make a service a singleton as below.
18. What is the provider in Angular?
In Angular, dependency injection is used to inject the dependencies of services, A Provider works as an instructor for dependency injection system to resolve the dependencies. When you create any service it comes with a default @Injectable decorator that contains a default property 'providedIn' which creates the provider for service.
@Injectable({
providedIn: 'root',
})
export class DataService {
}
You can inject the services in the root or particular module as well and you can limit the scope of a service to a particular component by using component providers.
@Component({
/* . . . . .*/
providers: [DataService]
})
19. Explain the dependency injection in Angular?
Dependency Injection (DI) is a design pattern. Angular provides it's own dependency injection to Angular applications to increase their efficiency and modularity.
Dependency is an object or class that another class needs to complete its operations, for example A 'UserComponent' needs 'UserService' to perform user operations.
Angular DI framework injects the dependencies when it's instantiating the class or component.
In angular it's mandatory to create the service with @Injecible decorator.
To get injected the service by dependency injection you need to specify providers.
@Injectable({
providedIn: 'root', // to inject the dependency in root
})
export class UserService {
}
//In user component constructor you can inject the dependency like this
constructor(userService: UserService){}
To configure providers at NgModule and Component level you can set the 'providers' metadata option of @Component and @NgModule decorators.
20. What is RxJS library?
RxJS (Reactive Extensions for JavaScript) is a library that uses the observable sequences for asynchronous and event-based or callback-based code. RxJS library has one core type
'Observable' and satellite types including (Observer, Schedulers, Subjects).
RxJS provides many operators to support the below features.
21. What are the observables in Angular?
In Angular, observables are used to achieve some common asynchronous operations as below.
22. What are the differences between Promises and Observables in Angular?
Observables are compared with Promises most of the time, there are a lot of differences in them as below.
23.What is the subscribe method in Angular?
You need to subscribe to the instance to use published values from Observable instances. For this, observable instances provide the subscribe method and pass an object to receive notifications.
// Create simple observable that emits three values
const testObservable = of(4, 5, 6);
// Create observer object
const tstObserver = {
next: value => console.log('Observer got a next value that is: ' + value),
error: err => console.error('Observer got an error: ' + err),
complete: () => console.log('Observer got a complete notification'),
};
// Execute with the observer object
testObservable.subscribe(tstObserver);
// Logs:
// Observer got a next value: 4
// Observer got a next value: 5
// Observer got a next value: 6
// Observer got a complete notification
24. How does routing work in Angular?
Angular configure routes in the AppRoutingModule file. To configure routes first import the AppRoutingModule file in your AppModule and add it to the imports array.
import { AppRoutingModule } from './app-routing.module'; // CLI imports AppRoutingModule
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [AppRoutingModule] // CLI adds AppRoutingModule to the AppModule's imports array
.....
})
To define and configure the routes perform below steps.
import { Routes, RouterModule } from '@angular/router'; // 1. CLI imports router
const routes: Routes = [ { path: 'first-route', component: FirstRoute },
{ path: 'second-route', component: SecondRoute }]; // 2. sets up routes constant where you define your routes
// configures NgModule imports and exports
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
// 3. configure routes
25. Explain the route guards?
A User can navigate anywhere to the application at a moment of time, but sometimes you want to control the user access for various reasons as below.
26.What is Root Module in Angular?
Every Angular application has at least one module, You bootstrap that module to launch the application. This module is called Root Module. When you create an angular application then you get by default one NgModule with the name AppModule called root module.
27. Explain the feature module and types of feature modules.
Angular provides one NgModule by default when you create any new angular application. As your application functionality grows then you can create a feature module responsible for a particular set of functionality. for example you can create routingModule for routes, for customer functionality customerModule etc. You can create a feature module using the below command and then you can import this feature module to your root module's import array.
ng generate module CustomerDashboard
There are 5 types of feature modules as below.
28. Explain the lazy loading of feature modules.
In Angular by default all NgModules are eager loaded means they load as soon as the app loads. But for large applications where there are many routes you should prefer
lazy loading. Lazy loading is a pattern that loads modules as needed. It improves loading time of application as initial size of bundle is less.
You can create a lazy loaded feature module as below.
29. What is the HTTP interceptor?
HTTP Interceptor intercepts and handles an HTTP request or response. You create your own interceptor by implementing the HttpInterceptor interface.
interface HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable>
}
In case of multiple interceptors, the first interceptor transforms the request before passing it to next with 'next.handle(transformedReq)' method.
30. Explain some common commands in Angular.
Angular provides many commands to perform operations as below.
31. How will you create the library in Angular?
Some applications provide general solutions like a unified interface, some data operations apps etc. Developers can create these general applications as a library
which can be reused in different applications via npm packages. An Angular library differs from an Angular Application in that it can not run on its own as it must be imported in any application.
You can create, build, run, lint an angular library with below commands.
ng generate library auth-lib // to create library
ng build my-lib
ng test my-lib
ng lint my-lib
32. How will you publish any angular library?
Once you are ready with your angular library you can publish it to NPM repositories with below commands.
ng build my-lib --prod
cd dist/my-lib
npm publish
Here --prod flag specify to use older compiler and runtime instead of using Ivy in angular 9.
33. How to update your angular applications to the latest version of angular?
You can run a basic update command to update the latest stable release of angular CLI and angular core.
ng update @angular/cli @angular/core
Above command will update your application to the latest angular CLI and angular core. You can also update from one major version to another by specifying the version as below.
ng update @angular/cli@^9 @angular/core@^9
To check other dependencies you can visit Angular Update Guide and to set any options
visit Angular ng update command.
34. What is Transpiling in Angular?
In Angular, Transpiling refers to the process of converting Typescript code into JavaScript code. It's done using a TypeScript compiler that's called a transpiler.
35. Describe the Bazel that was introduced in Angular 8.
Bazel is a build tool that works with angular CLI to build your application. The @angular/bazel package provides this build tool. To include bazel in an existing application use the below command.
ng add @angular/bazel
To use Bazel in a new application, first you need to install it globally using the below command.
npm install -g @angular/bazel
// and to create new application
ng new --collection=@angular/bazel
Now Bazel will be used behind the scene for the commands like ng build, ng serve. You can put the Bazel output in the dist/bin folder.
36. What is an Angular service worker?
Angular Service Worker is a script that runs in the browser and manages the caching for an application. It provides a good user
experience with performance and reliability.
It works as a network proxy that intercepts all the HTTP requests and decides how to respond to them. It can serve the request from cache if it is available.
Unlike Other Angular scripts, service worker is preserved after the user closes the tab. The next time the browser loads the application,
first the service worker loads and intercept all the requests without the need of the network.
37. On what port Angular runs by default?
By default, Angular runs on the 4200 port that could be configured.
38. Explain the SPA (Single Page Application).
SPA (Single Page Application) is a type of web application that provides a good user experience by dynamically loading the selected part of the application instead of loading the full application. SPA has good speed and performance.
39. What is an AOT compiler?
Browser does not understand Angular code directly, so compilation is required to convert that code into efficient JavaScript code. A ahead-of-time (AOT) compiler compiles the Angular and HTML code during the build phase so that compiled JavaScript code is available for the browser to download and run. AOT compiler compiles the code during build phase so it makes rendering to be fast in the browser. For more visit AOT Compiler.
39. How to implement authentication in Angular Application?
40. Where you will store the token in cookies, session storage or local storage?
1. List some new features in Angular 9
Angular 9 released on 6th Feb 2020 with a stable version 9.0.0 release. It's a major release of Angular that covers the Angular Framework, CLI, Angular Material and
Platform updates.
There are many new features provided in Angular 9 as below.
2. How to update to Angular version 9?
To update your project to Angular 9 First update your project to Latest Release of Angular 8 for better update experience as below.
ng update @angular/cli@8 @angular/core@8
Once you have updated to Angular 8 then update to Angular 9 or latest version of Angular as below.
ng update @angular/cli @angular/core
For detailed update changes follow Angular Official document Update to Angular 9.
3. What is Project Ivy in Angular 9?
Angular 9 has come with project Ivy with a lot of advantages as below. Ivy is a compiler and runtime. Angular version 9 allows all applications to use this Ivy compiler and runtime by default. There are many advantages of Ivy compiler and runtime.
4. What are Component Harnesses in Angular 9?
Normally component testing relies on implementation details, if a component library changes it's implementation then all the test dependent on that component needs to be updated.
But component harness API provides the capability of insulating or isolating for a test against the updates to component's internal changes in DOM structure.
So Component Harness provides an alternate approach to test the components. it will be available to component authors as a part of Component Dev Kit (CDK).
Multiple environments can be supported by component harnesses, as only single harness implementation can be used for both unit testing and end to end testing.
Let's take a look at the example of Component Harness.
it("should switch to customer data template", async () => {
expect(fixture.debugElement.query("customer-form")).toBeNull();
const select = await loader.getHarness(MatSelect);
await select.clickOptions({ text: "Bug" });
expect(fixture.debugElement.query("customer-form")).not.toBeNull();
});
5. What are the new options for 'providedIn' in Angular 9?
Angular services are added to the injector using @Injectable decorator. Angular 9 is providing 2 more options to inject the services with existing additional options as below.
6. How 'ng update' works in Angular 9?
Angular 9 has made 'ng update' more informative and reliable.
7. What are the improvements in IDE and language service in Angular 9?
You can see some improvements to the Angular Language Service extension on visual studio marketplace. There were some bugs that have been fixed. Some other improvements include:
1. How much will you rate yourself in Angular?
When you attend an interview, Interviewer may ask you to rate yourself in a specific Technology like Angular, So It's depend on your knowledge and work experience in Angular. The interviewer expects a realistic self-evaluation aligned with your qualifications.
2. What challenges did you face while working on Angular?
The challenges faced while working on Angular projects are highly dependent on one's specific work experience and the technology involved. You should explain any relevant challenges you encountered related to Angular during your previous projects.
3. What was your role in the last Project related to Angular?
This question is commonly asked in interviews to understand your specific responsibilities and the functionalities you implemented using Angular in your previous projects. Your answer should highlight your role, the tasks you were assigned, and the Angular features or techniques you utilized to accomplish those tasks.
4. How much experience do you have in Angular?
Here you can tell about your overall work experience on Angular.
5. Have you done any Angular Certification or Training?
Whether a candidate has completed any Angular certification or training is optional. While certifications and training are not essential requirements, they can be advantageous to have.
We have covered some frequently asked Angular Interview Questions and Answers to help you for your Interview. All these Essential Angular Interview Questions are targeted for mid level of experienced Professionals and freshers.
While attending any Angular Interview if you face any difficulty to answer any question please write to us at info@qfles.com. Our IT Expert team will find the best answer and will update on the portal. In case we find any new Angular questions, we will update the same here.