SlideShare a Scribd company logo
12
Most read
14
Most read
18
Most read
Top Infosys Angular Interview Questions to Boost Your
Preparation
If you are a fresher preparing for an Angular interview, these Infosys Angular interview questions will help you understand the
basics and boost your confidence.
Preparing for an Infosys Angular interview can feel overwhelming, especially if you're aiming to work with a leading IT giant like
Infosys. But don't worry! This guide will walk you through the recruitment process, from understanding the stages to mastering
the key Angular interview questions designed for Infosys. Whether you’re a fresher or an experienced professional, these tips
and questions will help you ace your Infosys Angular interview. Let’s dive in.
In this Interview Tutorial, we’ll explore the Infosys Angular interview questions and answers, including insights into the
recruitment process, technical rounds, Infosys Angular Interview Questions for Freshers, Infosys Angular Interview Questions
for Experienced, and strategies to excel in your interview.
The Infosys Angular interview process evaluates your ability to develop efficient and scalable web applications using Angular.
You can expect questions on key Angular fundamentals like components, modules, Angular Forms, services, and routing.
Additionally, scenario-based tasks will test your expertise in implementing state management using NgRx or RxJS. You may
also face questions about performance optimization, debugging, and integrating Angular with back-end services.
Understanding Angular testing frameworks like Jasmine and Karma, as well as following best practices, will give you a
competitive edge during the interview.
Infosys Angular Interview Questions For Freshers
What to Expect in the Infosys Angular Interview Process
Q.2 Explain MVVM architecture.
Ans: MVVM (Model-View-ViewModel) is a software architectural pattern that helps separate the UI logic from business logic,
making applications more maintainable and scalable. It consists of three key components:
Q.1 What is Angular, and what are its key features?
Ans: Angular is a TypeScript-based framework for building single-page applications (SPAs). Its key features include data
binding, dependency injection, directives, routing, and RxJS for reactive programming. It’s widely used for creating scalable
and interactive web apps.
The ViewModel fetches data from the Model and updates the View.
The ViewModel listens for user interactions in the View and updates the Model accordingly.
Data binding ensures that changes in the Model automatically reflect in the View.
Let's implement a simple example where we bind user input to a model using two-way data binding:
The Model represents the application's data structure. It manages data retrieval, storage, and business rules.
The ViewModel acts as an intermediary between the View and Model. It handles user interactions, business logic, and data
transformations before sending them to the View.
The View is the user interface that presents data to users. In Angular, this refers to the HTML templates that display
information from the Model.
2. View
1. Model
3. ViewModel
How MVVM Works:
Example of MVVM in Angular
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {
import { Component } from '@angular/core';
And the corresponding View ( ):
Ans: The Angular CLI is a command-line tool that simplifies tasks like initializing projects (
serve), generating components (ng generate), and running tests (ng test).
Two-way data binding: The View updates whenever the Model changes, and vice versa.
Separation of concerns: Business logic is managed in the ViewModel, keeping the View clean.
Scalability: Helps in building large applications efficiently.
MVVM architecture enhances modularity and makes code more maintainable in Angular applications.
), serving applications (
Ans: Lifecycle hooks allow you to execute custom logic at specific stages of a component's lifecycle. Common hooks include
ngOnInit, ngOnChanges, ngAfterViewInit, and ngOnDestroy.
Ans: Angular directives are used to manipulate the DOM or extend HTML functionality. Directives can be categorized as
structural (e.g., *ngFor, *ngIf) or attribute (e.g., [ngClass], [ngStyle]).
Ans: Dependency injection is a design pattern in Angular that allows services or dependencies to be provided to components
or other services. This improves modularity and testability.
Ans: Data binding in Angular establishes a connection between the application UI and the business logic. It includes one-way
binding (interpolation and property binding) and two-way binding (via [(ngModel)]). This ensures real-time updates between
the view and the model.
Enter Name:
Welcome, {{ userName }}!
userName: string = 'Shubham';
updateUserName(name: string) {
}
}
this.userName = name;
user.component.html
ng new ng
Key Takeaways:
Q.4 What is data binding in Angular?
Q.8 How does Angular handle forms?
Q.6 What are Angular lifecycle hooks?
Q.3 What is the role of Angular directives?
Q.7 What is dependency injection in Angular?
Q.5 How does Angular CLI simplify development?
Ans: Angular provides built-in support for unit testing with Jasmine and end-to-end testing with Protractor. Components and
services are tested using test files, ensuring application reliability and performance.
Ans: Angular supports two types of forms: template-driven forms and reactive forms. Template-driven forms rely on HTML
directives, while reactive forms use the FormControl and FormGroup classes for greater flexibility and validation.
Ans: Angular services are classes designed to share logic or data across multiple components. They are typically used for
business logic and are injected into components using dependency injection.
Ans:Pipes Angular are used to transform data in the template. For example, the uppercase pipe converts text to uppercase,
and the date pipe formats dates. You can also create custom pipes to fit specific needs.
Ans: Angular routing allows navigation between views in a single-page application. It is implemented using the RouterModule,
which maps URLs to components via route configurations.
Ans: Observables, part of RxJS, allow you to handle multiple values over time and provide powerful operators for transforming
and handling asynchronous data streams. On the other hand, promises resolve a single value. Observables are more flexible,
can be canceled, and are ideal for real-time data processing.
@Injectable({
{{ user.dateOfBirth | date:'shortDate' }}
import { Injectable } from '@angular/core';
Q.13 What are Angular services?
Q.11 What is the purpose of Angular pipes?
Q.10 How is testing done in Angular applications?
Q.9 What is Angular routing, and how is it implemented?
Q.12 What is the difference between observables and promises in Angular?
Example:
Example:
Q.15 What are Angular templates?
Ans: Angular templates are HTML files that define the structure and view of a component. They use Angular syntax, like {{
interpolation }} and ngIf, to dynamically render data and respond to user actions.
Q.14 How does Angular handle error handling in HTTP requests?
Ans: Angular uses the HttpClient module to make HTTP requests and the catchError operator from RxJS to catch and handle
errors in the response. Additionally, you can use HttpInterceptorto handle HTTP request errors globally.
Q.16 How can you create a custom structural directive in Angular?
Ans: A custom structural directive in Angular is used to modify the DOM layout by adding or removing elements dynamically. It
is created using the @Directive decorator and the TemplateRef and ViewContainerRef services.
Example:
Example:
Welcome, {{ username }}
providedIn: 'root'
})
export class UserService {
getUser() {
}
}
return { name: 'Shubham', age: 25 };
constructor(private http: HttpClient) {}
// Example of a Custom Structural Directive
getData() {
this.http.get('api/data').pipe(
catchError(error => {
console.error('Error occurred:', error);
throw error;
})
).subscribe(data => console.log(data));
}
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
Click Me
@Input() set appHighlight(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
// Usage in a Template
// This will display the paragraph only if showContent is true
<p *appHighlight="showContent">This is a highlighted text.</p>
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private templateRef: TemplateRef, private viewContainer: ViewContainerRef) {}
(event),
Read More: DOM and BOM in JavaScript
Ans: Angular uses event binding to listen to user actions like clicks, key presses, etc. The syntax for event binding is
which links a DOM event to a method in the component class.
Ans: Dependency Injection (DI) is a design pattern in Angular that allows components and services to receive dependencies
instead of creating them manually. It promotes modularity, reusability, and testability in applications.
In Angular, a dependency is typically a service that provides functionality across multiple components. Instead of manually
instantiating these services, Angular injects them where needed.
Q.17 How does Angular handle event binding?
Q.18 Explain the concept of Dependency Injection.
Example:
Understanding Dependency Injection
Example of Dependency Injection
Let’s consider a that displays messages.
We can inject this service into a component to use its functionality:
NotificationService
import { Injectable } from '@angular/core';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
import { Component, OnInit } from '@angular/core';
import { NotificationService } from '../notification.service';
@Injectable({
providedIn: 'root' // Makes the service available throughout the app
})
export class NotificationService {
showMessage(message: string) {
}
}
console.log(`Notification: ${message}`);
Example:
Example:
Key Takeaways:
Services: Services are marked with @Injectable to make them injectable.
Injection: The service is injected into the component via the constructor.
ProvidedIn: Using providedIn: 'root' ensures the service is available globally.
This approach enables Angular to manage dependencies efficiently, promoting scalability and maintainability.
Ans: ngOnInit isa Component lifecycle hook in Angular that is called after the component is initialized. It's used to perform
component initialization logic like data fetching or setting up subscriptions.
Ans: The Angular compiler converts templates and components into executable JavaScript code. This occurs during the build
phase using AOT (Ahead-of-Time compilation), which improves performance.
Here are some commonly asked Infosys Angular interview questions for 3 years experience. If you have around three years of
experience in Angular, these questions will help you understand the key concepts, best practices, and real-world scenarios you
might face during your interview at Infosys.
Ans: Lazy loading in Angular is a technique to load modules only when they are needed, which reduces the initial load time of
the application. This is especially useful for large applications with multiple routes.
ngOnInit() {
this.fetchData();
ngOnInit() {
}
}
this.notificationService.showMessage('User Component Loaded');
constructor(private notificationService: NotificationService) { }
const routes: Routes = [
{ path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) }
];
Q.21 What is ngOnInit in Angular?
Q.20 What is the role of the Angular compiler?
Q.19 What are lazy loading modules in Angular?
Infosys Angular Interview Questions for Intermediates
Q.24 What are Angular directives?
Ans: Angular directives are special markers on elements that tell Angular to do something with the DOM. There are three types:
structural directives (e.g., *ngIf, *ngFor), attribute directives (e.g., ngClass, ngStyle), and component directives
(components themselves).
Q.23 What is two-way data binding in Angular?
Ans: Two-way Data binding in Angularallows for synchronization between the component's property and the view. It is
implemented using the [(ngModel)] directive.
Q.25 What is dependency injection in Angular?
Ans: Dependency injection in Angular is a design pattern used to supply dependencies (like services) to components or other
services. Angular’s dependency injection system allows you to keep your code modular and testable.
Q.22 What is the difference between ngOnInit and constructor in Angular?
Ans: ngOnInit is a lifecycle hook called after the component’s constructor, which is used for component initialization, whereas
the constructor is called when the component is instantiated. ngOnInit is best for initialization tasks that depend on input
proper ties.
Q.26 How can you pass data from a parent component to a child component in Angular?
Ans: Data is passed from a parent to a child component using input bindings through the
component.
decorator in the child
}
{{ userName }}
@Input() user: any;
@Input()
Example:
Example:
Q.28 What is Angular CLI?
Ans:Angular CLI(Command Line Interface) is a powerful tool that simplifies development tasks like creating components and
services and managing configurations in an Angular application.
Q.30 What are Angular modules?
Ans: Angular modules are used to group related components, services, and other code. The root module is typically
and additional feature modules can be created to organize an application.
Q.31 What are guards in Angular routing?
Ans: Guards in Angular routing are used to control navigation. You can use guards to prevent or allow navigation based on
conditions like user authentication or authorization. Guards include CanActivate, CanDeactivate, CanLoad, and others.
Q.33 What is the zone.js library in Angular?
Ans: Zone.js is a library used in Angular to manage asynchronous operations. It helps detect changes in the application by
keeping track of asynchronous tasks and ensuring that Angular can update the view when necessary.
Q.32 How do you optimize performance in Angular?
Ans: Performance optimization in Angular can be achieved by techniques such as lazy loading in angular, AOT compilation,
change detection strategy optimization, and trackBy in *ngFor loops.
Q.29 What is the difference between ngIf and ngSwitch?
Ans: ngIf is used to conditionally include or exclude elements from the DOM, while ngSwitch is used to display multiple
elements based on a single expression conditionally.
Q.27 How do you handle error scenarios globally in Angular?
Ans: Global error handling in Angular can be implemented using the ErrorHandler class. Custom error handlers allow you to
centralize error reporting and management.
// Example of Global Error Handler
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: any): void {
}
}
console.error('An error occurred:', error);
// Custom logic, e.g., logging to a server
@NgModule({
providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }]
})
export class AppModule {}
AppModule,
Q.34 What is change detection in Angular?
Ans: Change detection in Angular is the process of checking the component’s state and updating the view accordingly.
Angular uses a dirty checking mechanism to determine when to update the DOM based on changes in component properties.
Q.37 What is Ahead-of-Time (AOT) compilation in Angular?
Ans: AOT compilation converts Angular templates into optimized JavaScript code during the build process. This reduces the
application load time and increases performance by eliminating the need for the browser to compile templates at runtime.
Q.35 What is the purpose of the ng-content directive in Angular?
Ans: The ng-content directive in Angular is used for content projection, which allows you to insert external content into a
component’s template. It’s useful for creating reusable components like modals and cards.
Q.36 What is the purpose of Angular's Change Detection mechanism?
Ans: Angular's Change Detection mechanism ensures that the application view reflects the current state of the data model. It
detects changes in the component state and updates the DOM accordingly. Angular uses a zone.js library to intercept
asynchronous operations like HTTP requests or user events and triggers the change detection cycle.
For professionals with experience, these Infosys Angular interview questions for experienced will help you demonstrate your
expertise in Angular, including advanced concepts, best practices, and real-world applications.
Example:
Infosys Angular Interview Questions for Experienced
@Component({
selector: 'app-example',
template: `{{ counter }}`
})
export class AppExample {
counter = 0;
This is projected content
constructor(private cdr: ChangeDetectorRef) {}
incrementCounter() {
}
}
setTimeout(() => {
this.counter++;
this.cdr.detectChanges(); // Manually triggers change detection
}, 1000);
// Example of triggering change detection manually using ChangeDetectorRef
import { Component, ChangeDetectorRef } from '@angular/core';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
// Example of lazy loading configuration
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
// Example using Renderer2 to set a class on an element
import { Component, ElementRef, Renderer2 } from '@angular/core';
@Component({
selector: 'app-example',
template: `Renderer2 Example`
})
export class AppExample {
constructor(private el: ElementRef, private renderer: Renderer2) {
// Enabling AOT in Angular
// Use the following command to build the application with AOT enabled
ng build --aot
const routes: Routes = [
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
];
AOT also catches template errors during the build process, making debugging easier before deployment.
Ans: Angular's Renderer2 service abstracts the DOM manipulation logic, allowing you to modify the DOM safely, even in
environments where direct DOM access is not possible, such as server-side rendering or Web Workers.
Ans: Lazy loading in Angular improves performance by loading modules only when they are needed. You can achieve this
using the loadChildren property in the Angular Router configuration.
Q.39 What is the role of Angular's Renderer2 service?
Q.38 How can you implement lazy loading with Angular routes?
@Injectable({ providedIn: 'root' })
export class GlobalService {
getMessage() {
}
}
return 'Service available globally';
@Component({
selector: 'app-example',
template: `{{ data }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppExample {
// Example of providing a service at the component level
import { Injectable } from '@angular/core';
@Component({
selector: 'app-local',
template: `{{ message }}`,
providers: [LocalService] // Local service provided here
})
export class LocalComponent {
constructor(private localService: LocalService) {
}
}
this.message = this.localService.getMessage();
}
}
this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
// Example of OnPush change detection
import { Component, ChangeDetectionStrategy, Input } from '@angular/core';
Q.40 What is Angular's Dependency Injection (DI) hierarchy?
Ans: Angular's DI hierarchy allows services to be provided at different levels, such as the root module, feature module, or
component level. The hierarchical structure ensures that child components inherit services provided at a higher level
unless explicitly overridden.
Q.41 How do you optimize Angular applications for performance?
Ans: Optimizing Angular applications involves several techniques, including:
Using AOT compilation to reduce runtime overhead.
Implementing lazy loading for modules.
Using OnPush change detection for immutability.
Minimizing the use of global variables and services.
@Input() data: string;
}
@Component({
selector: 'app-form',
template: ``
})
export class FormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
// Example using FormBuilder
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
// Example of an Angular interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
return next.handle(clonedRequest);
}
}
Read More: Understanding Local and Global Variables in JavaScript
Ans: Securing Angular applications involves:
Using route guards like CanActivate to restrict unauthorized access.
Securing API endpoints with tokens.
Using Angular's DomSanitizer to prevent XSS attacks.
Ans: Angular's FormBuilder simplifies the creation of reactive forms by reducing boilerplate code. It provides methods to
create FormGroup and FormControl.
Ans: Angular interceptors are used to modify HTTP requests or responses globally. They are implemented by creating a
service that implements the HttpInterceptor interface.
Q.43 How can you secure Angular applications?
Q.44 How does Angular's FormBuilder simplify reactive forms?
Q.42 What are Angular interceptors, and how are they implemented?
} }
name: ['']
});
@Component({
selector: 'app-user',
template: `User ID: {{ userId }}`
})
export class UserComponent implements OnInit {
userId: string;
constructor(private route: ActivatedRoute) {}
// Example of accessing route parameters
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
}
}
return !!localStorage.getItem('userToken'); // Example condition
// Example of CanActivate route guard
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
ngOnInit() {
}
}
this.userId = this.route.snapshot.paramMap.get('id'); // Accessing parameter using snapshot
Q.45 How does Angular handle route guards?
Ans: Angular route guards, like CanActivate, control navigation based on conditions, ensuring that only authorized users can
access specific routes.
Q.46 How does Angular handle routing with parameters?
Ans: Angular routing allows you to pass parameters in the URL, which can be accessed in the component using the
ActivatedRoute service. Parameters can be optional or required and can be accessed using snapshot or observable methods.
Q.47 What is the difference between Template-Driven Forms and Reactive Forms in
Angular?
Ans: Angular provides two ways to build forms:
Ans: The ngOnInit lifecycle hook is called once when the component is initialized, whereas ngAfterViewInit is called after the
component's view has been fully initialized and rendered. Use ngOnInit for initialization logic and ngAfterViewInit for
operations that require interaction with the view.
Template-Driven Forms: Uses Angular directives like ngModel to bind form controls to data models. They are simpler but
less scalable for complex forms.
Reactive Forms:Angular Model-Driven (Reactive) Forms Provide more control and flexibility by using FormGroup and
FormControl objects. Reactive forms are more scalable for larger forms.
@Component({
selector: 'app-example',
template: ``
})
export class ExampleComponent {
form: FormGroup;
ngOnInit() {
}
this.message = 'ngOnInit called';
console.log('ngOnInit called');
constructor(private fb: FormBuilder) {
}
}
this.form = this.fb.group({
name: ['']
});
ngAfterViewInit() {
this.message += ' and ngAfterViewInit called';
console.log('ngAfterViewInit called');
// Example of reactive form with FormBuilder
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
// Example showing ngOnInit and ngAfterViewInit lifecycle hooks
import { Component, OnInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-lifecycle',
template: `{{ message }}`
})
export class LifecycleComponent implements OnInit, AfterViewInit {
message: string;
Q.48 What is the difference between Angular's ngOnInit and ngAfterViewInit lifecycle
hooks?
}
}
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
// Example of an attribute directive
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
}
}
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
} }
const isAuthenticated = !!localStorage.getItem('authToken'); // Check authentication status
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
// Example of using route guards for authorization
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
Q.50 How do you implement authentication and authorization in Angular?
Ans: Authentication and authorization in Angular can be handled using services that interact with a backend API for login and
role validation. You can secure routes with route guards to restrict access based on user roles and authentication status.
Common techniques include using JWT tokens for authentication.
Q.49 What are Angular Directives, and how do they differ from Components?
Ans: Angular directives are classes that allow you to manipulate the DOM in various ways, such as creating custom behavior or
altering the appearance of elements. They are classified into three types: Structural Directives (e.g., *ngIf, *ngFor), Attribute
Directives (e.g., ngClass, ngStyle), and Component Directives.
Components are a type of directive with a template, while other directives do not have their own templates.
Ans:
Ans: Angular supports PWAs using the
experiences using service workers.
: Defines reusable HTML templates that are rendered dynamically.
: Groups multiple elements without adding extra DOM nodes.
Ans: NgRx is a reactive state management library for Angular. Implementation steps:
Install NgRx: ng add @ngrx/store.
Define actions, reducers, and selectors.
Ans: Angular Universal enables SSR, improving SEO and performance. To implement SSR:
Install Angular Universal: ng add @nguniversal/express-engine.
Build the app: npm run build:ssr.
Run the server: npm run serve:ssr.
Ans: Angular handles memory leaks using automatic garbage collection. However, developers should follow best practices:
Unsubscribe from Observables using takeUntil or async pipe.
Detach event listeners to avoid reference leaks.
Use ngOnDestroy() to clean up subscriptions.
Limit DOM element manipulations and use trackBy in *ngFor.
Ans: The trackBy function in *ngFor improves performance by preventing unnecessary DOM updates. Instead of re-rendering
the entire list when data changes, it updates only the modified elements.
Ans: Web Workers in Angular run JavaScript in the background, preventing UI blocking. They improve performance by handling
heavy computations separately. Angular provides Web Workers using ng generate web-worker.
Ans: Angular's ViewEncapsulation controls how styles are applied to components. It helps encapsulate styles within a
component to avoid conflicts with global styles. Angular provides three types of encapsulation:
Emulated (default): Uses scoped styles but allows inheritance.
ShadowDom: Uses native shadow DOM for true encapsulation.
None: Applies styles globally.
JWT tokens are typically stored in localStorage or sessionStorage for client-side authentication, and the backend verifies the
token before granting access to protected routes.
package. PWAs provide offline support, faster loading, and app-like
Q.53 What is the role of trackBy in Angular's *ngFor directive?
Q.51 What is the purpose of the Angular ViewEncapsulation feature?
Q.57 What is the purpose of ng-template and ng-container in Angular?
Q.56 How does Angular handle progressive web applications (PWAs)?
Q.58 How do you implement state management in Angular using NgRx?
Q.52 How does Angular handle memory leaks, and how can they be prevented?
Q.55 What are Web Workers in Angular, and how can they improve performance?
Q.54 How do you implement a server-side rendering (SSR) with Angular Universal?
ng-template
ng-container
@angular/pwa
Use
(a) Two-way data binding
(b) Dependency Injection
(c) Component-based architecture
(d) All of the above
View Answer ⬇
to dispatch and select state updates.
Read More: Angular Interview Questions and Answers
Ans: Secure authentication token handling involves:
Storing tokens in HttpOnly cookies instead of localStorage.
Using Interceptor to add tokens to API requests.
Implementing expiration checks and auto-logout mechanisms.
(a) AngularJS is based on JavaScript, while Angular is based on TypeScript
(b) AngularJS uses controllers, while Angular uses components
(c) Angular is faster and supports mobile development
(d) All of the above
View Answer ⬇
Ans: Standalone components simplify Angular development by removing the need for
Faster loading with tree shaking.
Easier code maintenance.
Better modularization and reusability.
. Benefits include:
This article covers the Top 50 Infosys Angular Interview Questions for freshers, intermediates, and experienced candidates. It
highlights key Angular concepts such as dependency injection, routing, Angular modules, change detection, and lazy loading.
These questions are designed to test your understanding of Angular's core features and practical implementations, ensuring
you're well-prepared for your Infosys interview. Detailed answers with examples are provided to help you grasp and apply
Angular concepts efficiently. Whether you're new to Angular or preparing for an advanced role, this guide is a valuable resource
for success.
Enhance your skills with the Angular Certification Online Training from ScholarHat. Master Angular through hands-on projects
and expert insights to accelerate your career growth!
Store
NgModule
Q 3: What are Angular lifecycle hooks?
Q 1: What are the key features of Angular?
Q 2: What is the difference between AngularJS and Angular?
Q.59 What are the benefits of using standalone components in Angular?
Q.60 How can you handle authentication tokens securely in an Angular application?
Summary
Infosys Angular Interview Questions
(a) Using Template-driven forms
(b) Using Reactive forms
(c) Both (a) and (b)
(d) None of the above
View Answer ⬇
(a) Functions that execute during the component lifecycle
(b) A feature that speeds up Angular applications
(c) Methods to manage API calls
(d) A tool for debugging components
View Answer ⬇
(a) To share data between components
(b) To handle API calls
(c) To implement business logic separately from components
(d) All of the above
View Answer ⬇
Q 5: What is the purpose of Angular Services?
Q 4: How does Angular handle form validation?

More Related Content

Similar to Infosys Angular Interview Questions PDF By ScholarHat (20)

PPTX
Introduction to single page application with angular js
Mindfire Solutions
 
PDF
The Role of Angular Services in Web Development.pdf
gauravpareekhawkscod
 
PPTX
angularjs_vs_angular_the_key_differences_between_javascript_and_typescript.pptx
sarah david
 
PDF
Modern webtechnologies
Besjan Xhika
 
PPTX
The Basics Angular JS
OrisysIndia
 
PDF
Angularjs interview questions and answers
Anil Singh
 
PPTX
Angular Basics.pptx
AshokKumar616995
 
PPTX
angularjs_vs_angular_the_key_differences_between_javascript_and_typescript.pptx
sarah david
 
PDF
AngularJS Basics
Ravi Mone
 
PPTX
AngularJS = Browser applications on steroids
Maurice De Beijer [MVP]
 
PPT
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
PPTX
What are the key distinctions between Angular and AngularJS?
Albiorix Technology
 
PDF
AngularJS
Hiten Pratap Singh
 
PDF
angularjs-vs-angular-the-key-differences-between-javascript-and-typescript
Cuneiform Consulting Pvt Ltd.
 
PPTX
Angular Javascript Tutorial with command
ssuser42b933
 
PDF
MVC Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
angularjs_vs_angular_the_key_differences_between_javascript_and_typescript.pptx
sarah david
 
PPT
introduction to Angularjs basics
Ravindra K
 
PPTX
Angular js workshop
Rolands Krumbergs
 
Introduction to single page application with angular js
Mindfire Solutions
 
The Role of Angular Services in Web Development.pdf
gauravpareekhawkscod
 
angularjs_vs_angular_the_key_differences_between_javascript_and_typescript.pptx
sarah david
 
Modern webtechnologies
Besjan Xhika
 
The Basics Angular JS
OrisysIndia
 
Angularjs interview questions and answers
Anil Singh
 
Angular Basics.pptx
AshokKumar616995
 
angularjs_vs_angular_the_key_differences_between_javascript_and_typescript.pptx
sarah david
 
AngularJS Basics
Ravi Mone
 
AngularJS = Browser applications on steroids
Maurice De Beijer [MVP]
 
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
What are the key distinctions between Angular and AngularJS?
Albiorix Technology
 
angularjs-vs-angular-the-key-differences-between-javascript-and-typescript
Cuneiform Consulting Pvt Ltd.
 
Angular Javascript Tutorial with command
ssuser42b933
 
MVC Interview Questions PDF By ScholarHat
Scholarhat
 
angularjs_vs_angular_the_key_differences_between_javascript_and_typescript.pptx
sarah david
 
introduction to Angularjs basics
Ravindra K
 
Angular js workshop
Rolands Krumbergs
 

More from Scholarhat (20)

PDF
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
React Router Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Java Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Scholarhat
 
PDF
DBMS Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
API Testing Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
System Design Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Python Viva Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Linux Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Kubernetes Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Collections in Java Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
CI CD Pipeline Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Azure DevOps Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
UIUX Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Python Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
OOPS JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
PDF
Git Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Redux Interview Questions PDF By ScholarHat
Scholarhat
 
React Router Interview Questions PDF By ScholarHat
Scholarhat
 
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Java Interview Questions PDF By ScholarHat
Scholarhat
 
Java Interview Questions for 10+ Year Experienced PDF By ScholarHat
Scholarhat
 
DBMS Interview Questions PDF By ScholarHat
Scholarhat
 
API Testing Interview Questions PDF By ScholarHat
Scholarhat
 
System Design Interview Questions PDF By ScholarHat
Scholarhat
 
Python Viva Interview Questions PDF By ScholarHat
Scholarhat
 
Linux Interview Questions PDF By ScholarHat
Scholarhat
 
Kubernetes Interview Questions PDF By ScholarHat
Scholarhat
 
Collections in Java Interview Questions PDF By ScholarHat
Scholarhat
 
CI CD Pipeline Interview Questions PDF By ScholarHat
Scholarhat
 
Azure DevOps Interview Questions PDF By ScholarHat
Scholarhat
 
TypeScript Interview Questions PDF By ScholarHat
Scholarhat
 
UIUX Interview Questions PDF By ScholarHat
Scholarhat
 
Python Interview Questions PDF By ScholarHat
Scholarhat
 
OOPS JavaScript Interview Questions PDF By ScholarHat
Scholarhat
 
Git Interview Questions PDF By ScholarHat
Scholarhat
 
Ad

Recently uploaded (20)

PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Ad

Infosys Angular Interview Questions PDF By ScholarHat

  • 1. Top Infosys Angular Interview Questions to Boost Your Preparation If you are a fresher preparing for an Angular interview, these Infosys Angular interview questions will help you understand the basics and boost your confidence. Preparing for an Infosys Angular interview can feel overwhelming, especially if you're aiming to work with a leading IT giant like Infosys. But don't worry! This guide will walk you through the recruitment process, from understanding the stages to mastering the key Angular interview questions designed for Infosys. Whether you’re a fresher or an experienced professional, these tips and questions will help you ace your Infosys Angular interview. Let’s dive in. In this Interview Tutorial, we’ll explore the Infosys Angular interview questions and answers, including insights into the recruitment process, technical rounds, Infosys Angular Interview Questions for Freshers, Infosys Angular Interview Questions for Experienced, and strategies to excel in your interview. The Infosys Angular interview process evaluates your ability to develop efficient and scalable web applications using Angular. You can expect questions on key Angular fundamentals like components, modules, Angular Forms, services, and routing. Additionally, scenario-based tasks will test your expertise in implementing state management using NgRx or RxJS. You may also face questions about performance optimization, debugging, and integrating Angular with back-end services. Understanding Angular testing frameworks like Jasmine and Karma, as well as following best practices, will give you a competitive edge during the interview. Infosys Angular Interview Questions For Freshers What to Expect in the Infosys Angular Interview Process
  • 2. Q.2 Explain MVVM architecture. Ans: MVVM (Model-View-ViewModel) is a software architectural pattern that helps separate the UI logic from business logic, making applications more maintainable and scalable. It consists of three key components: Q.1 What is Angular, and what are its key features? Ans: Angular is a TypeScript-based framework for building single-page applications (SPAs). Its key features include data binding, dependency injection, directives, routing, and RxJS for reactive programming. It’s widely used for creating scalable and interactive web apps. The ViewModel fetches data from the Model and updates the View. The ViewModel listens for user interactions in the View and updates the Model accordingly. Data binding ensures that changes in the Model automatically reflect in the View. Let's implement a simple example where we bind user input to a model using two-way data binding: The Model represents the application's data structure. It manages data retrieval, storage, and business rules. The ViewModel acts as an intermediary between the View and Model. It handles user interactions, business logic, and data transformations before sending them to the View. The View is the user interface that presents data to users. In Angular, this refers to the HTML templates that display information from the Model. 2. View 1. Model 3. ViewModel How MVVM Works: Example of MVVM in Angular @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent { import { Component } from '@angular/core';
  • 3. And the corresponding View ( ): Ans: The Angular CLI is a command-line tool that simplifies tasks like initializing projects ( serve), generating components (ng generate), and running tests (ng test). Two-way data binding: The View updates whenever the Model changes, and vice versa. Separation of concerns: Business logic is managed in the ViewModel, keeping the View clean. Scalability: Helps in building large applications efficiently. MVVM architecture enhances modularity and makes code more maintainable in Angular applications. ), serving applications ( Ans: Lifecycle hooks allow you to execute custom logic at specific stages of a component's lifecycle. Common hooks include ngOnInit, ngOnChanges, ngAfterViewInit, and ngOnDestroy. Ans: Angular directives are used to manipulate the DOM or extend HTML functionality. Directives can be categorized as structural (e.g., *ngFor, *ngIf) or attribute (e.g., [ngClass], [ngStyle]). Ans: Dependency injection is a design pattern in Angular that allows services or dependencies to be provided to components or other services. This improves modularity and testability. Ans: Data binding in Angular establishes a connection between the application UI and the business logic. It includes one-way binding (interpolation and property binding) and two-way binding (via [(ngModel)]). This ensures real-time updates between the view and the model. Enter Name: Welcome, {{ userName }}! userName: string = 'Shubham'; updateUserName(name: string) { } } this.userName = name; user.component.html ng new ng Key Takeaways: Q.4 What is data binding in Angular? Q.8 How does Angular handle forms? Q.6 What are Angular lifecycle hooks? Q.3 What is the role of Angular directives? Q.7 What is dependency injection in Angular? Q.5 How does Angular CLI simplify development?
  • 4. Ans: Angular provides built-in support for unit testing with Jasmine and end-to-end testing with Protractor. Components and services are tested using test files, ensuring application reliability and performance. Ans: Angular supports two types of forms: template-driven forms and reactive forms. Template-driven forms rely on HTML directives, while reactive forms use the FormControl and FormGroup classes for greater flexibility and validation. Ans: Angular services are classes designed to share logic or data across multiple components. They are typically used for business logic and are injected into components using dependency injection. Ans:Pipes Angular are used to transform data in the template. For example, the uppercase pipe converts text to uppercase, and the date pipe formats dates. You can also create custom pipes to fit specific needs. Ans: Angular routing allows navigation between views in a single-page application. It is implemented using the RouterModule, which maps URLs to components via route configurations. Ans: Observables, part of RxJS, allow you to handle multiple values over time and provide powerful operators for transforming and handling asynchronous data streams. On the other hand, promises resolve a single value. Observables are more flexible, can be canceled, and are ideal for real-time data processing. @Injectable({ {{ user.dateOfBirth | date:'shortDate' }} import { Injectable } from '@angular/core'; Q.13 What are Angular services? Q.11 What is the purpose of Angular pipes? Q.10 How is testing done in Angular applications? Q.9 What is Angular routing, and how is it implemented? Q.12 What is the difference between observables and promises in Angular? Example: Example:
  • 5. Q.15 What are Angular templates? Ans: Angular templates are HTML files that define the structure and view of a component. They use Angular syntax, like {{ interpolation }} and ngIf, to dynamically render data and respond to user actions. Q.14 How does Angular handle error handling in HTTP requests? Ans: Angular uses the HttpClient module to make HTTP requests and the catchError operator from RxJS to catch and handle errors in the response. Additionally, you can use HttpInterceptorto handle HTTP request errors globally. Q.16 How can you create a custom structural directive in Angular? Ans: A custom structural directive in Angular is used to modify the DOM layout by adding or removing elements dynamically. It is created using the @Directive decorator and the TemplateRef and ViewContainerRef services. Example: Example: Welcome, {{ username }} providedIn: 'root' }) export class UserService { getUser() { } } return { name: 'Shubham', age: 25 }; constructor(private http: HttpClient) {} // Example of a Custom Structural Directive getData() { this.http.get('api/data').pipe( catchError(error => { console.error('Error occurred:', error); throw error; }) ).subscribe(data => console.log(data)); } import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators';
  • 6. Click Me @Input() set appHighlight(condition: boolean) { if (condition) { this.viewContainer.createEmbeddedView(this.templateRef); } else { this.viewContainer.clear(); } } } // Usage in a Template // This will display the paragraph only if showContent is true <p *appHighlight="showContent">This is a highlighted text.</p> @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private templateRef: TemplateRef, private viewContainer: ViewContainerRef) {} (event), Read More: DOM and BOM in JavaScript Ans: Angular uses event binding to listen to user actions like clicks, key presses, etc. The syntax for event binding is which links a DOM event to a method in the component class. Ans: Dependency Injection (DI) is a design pattern in Angular that allows components and services to receive dependencies instead of creating them manually. It promotes modularity, reusability, and testability in applications. In Angular, a dependency is typically a service that provides functionality across multiple components. Instead of manually instantiating these services, Angular injects them where needed. Q.17 How does Angular handle event binding? Q.18 Explain the concept of Dependency Injection. Example: Understanding Dependency Injection
  • 7. Example of Dependency Injection Let’s consider a that displays messages. We can inject this service into a component to use its functionality: NotificationService import { Injectable } from '@angular/core'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { import { Component, OnInit } from '@angular/core'; import { NotificationService } from '../notification.service'; @Injectable({ providedIn: 'root' // Makes the service available throughout the app }) export class NotificationService { showMessage(message: string) { } } console.log(`Notification: ${message}`);
  • 8. Example: Example: Key Takeaways: Services: Services are marked with @Injectable to make them injectable. Injection: The service is injected into the component via the constructor. ProvidedIn: Using providedIn: 'root' ensures the service is available globally. This approach enables Angular to manage dependencies efficiently, promoting scalability and maintainability. Ans: ngOnInit isa Component lifecycle hook in Angular that is called after the component is initialized. It's used to perform component initialization logic like data fetching or setting up subscriptions. Ans: The Angular compiler converts templates and components into executable JavaScript code. This occurs during the build phase using AOT (Ahead-of-Time compilation), which improves performance. Here are some commonly asked Infosys Angular interview questions for 3 years experience. If you have around three years of experience in Angular, these questions will help you understand the key concepts, best practices, and real-world scenarios you might face during your interview at Infosys. Ans: Lazy loading in Angular is a technique to load modules only when they are needed, which reduces the initial load time of the application. This is especially useful for large applications with multiple routes. ngOnInit() { this.fetchData(); ngOnInit() { } } this.notificationService.showMessage('User Component Loaded'); constructor(private notificationService: NotificationService) { } const routes: Routes = [ { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) } ]; Q.21 What is ngOnInit in Angular? Q.20 What is the role of the Angular compiler? Q.19 What are lazy loading modules in Angular? Infosys Angular Interview Questions for Intermediates
  • 9. Q.24 What are Angular directives? Ans: Angular directives are special markers on elements that tell Angular to do something with the DOM. There are three types: structural directives (e.g., *ngIf, *ngFor), attribute directives (e.g., ngClass, ngStyle), and component directives (components themselves). Q.23 What is two-way data binding in Angular? Ans: Two-way Data binding in Angularallows for synchronization between the component's property and the view. It is implemented using the [(ngModel)] directive. Q.25 What is dependency injection in Angular? Ans: Dependency injection in Angular is a design pattern used to supply dependencies (like services) to components or other services. Angular’s dependency injection system allows you to keep your code modular and testable. Q.22 What is the difference between ngOnInit and constructor in Angular? Ans: ngOnInit is a lifecycle hook called after the component’s constructor, which is used for component initialization, whereas the constructor is called when the component is instantiated. ngOnInit is best for initialization tasks that depend on input proper ties. Q.26 How can you pass data from a parent component to a child component in Angular? Ans: Data is passed from a parent to a child component using input bindings through the component. decorator in the child } {{ userName }} @Input() user: any; @Input() Example: Example:
  • 10. Q.28 What is Angular CLI? Ans:Angular CLI(Command Line Interface) is a powerful tool that simplifies development tasks like creating components and services and managing configurations in an Angular application. Q.30 What are Angular modules? Ans: Angular modules are used to group related components, services, and other code. The root module is typically and additional feature modules can be created to organize an application. Q.31 What are guards in Angular routing? Ans: Guards in Angular routing are used to control navigation. You can use guards to prevent or allow navigation based on conditions like user authentication or authorization. Guards include CanActivate, CanDeactivate, CanLoad, and others. Q.33 What is the zone.js library in Angular? Ans: Zone.js is a library used in Angular to manage asynchronous operations. It helps detect changes in the application by keeping track of asynchronous tasks and ensuring that Angular can update the view when necessary. Q.32 How do you optimize performance in Angular? Ans: Performance optimization in Angular can be achieved by techniques such as lazy loading in angular, AOT compilation, change detection strategy optimization, and trackBy in *ngFor loops. Q.29 What is the difference between ngIf and ngSwitch? Ans: ngIf is used to conditionally include or exclude elements from the DOM, while ngSwitch is used to display multiple elements based on a single expression conditionally. Q.27 How do you handle error scenarios globally in Angular? Ans: Global error handling in Angular can be implemented using the ErrorHandler class. Custom error handlers allow you to centralize error reporting and management. // Example of Global Error Handler @Injectable() export class GlobalErrorHandler implements ErrorHandler { handleError(error: any): void { } } console.error('An error occurred:', error); // Custom logic, e.g., logging to a server @NgModule({ providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }] }) export class AppModule {} AppModule,
  • 11. Q.34 What is change detection in Angular? Ans: Change detection in Angular is the process of checking the component’s state and updating the view accordingly. Angular uses a dirty checking mechanism to determine when to update the DOM based on changes in component properties. Q.37 What is Ahead-of-Time (AOT) compilation in Angular? Ans: AOT compilation converts Angular templates into optimized JavaScript code during the build process. This reduces the application load time and increases performance by eliminating the need for the browser to compile templates at runtime. Q.35 What is the purpose of the ng-content directive in Angular? Ans: The ng-content directive in Angular is used for content projection, which allows you to insert external content into a component’s template. It’s useful for creating reusable components like modals and cards. Q.36 What is the purpose of Angular's Change Detection mechanism? Ans: Angular's Change Detection mechanism ensures that the application view reflects the current state of the data model. It detects changes in the component state and updates the DOM accordingly. Angular uses a zone.js library to intercept asynchronous operations like HTTP requests or user events and triggers the change detection cycle. For professionals with experience, these Infosys Angular interview questions for experienced will help you demonstrate your expertise in Angular, including advanced concepts, best practices, and real-world applications. Example: Infosys Angular Interview Questions for Experienced @Component({ selector: 'app-example', template: `{{ counter }}` }) export class AppExample { counter = 0; This is projected content constructor(private cdr: ChangeDetectorRef) {} incrementCounter() { } } setTimeout(() => { this.counter++; this.cdr.detectChanges(); // Manually triggers change detection }, 1000); // Example of triggering change detection manually using ChangeDetectorRef import { Component, ChangeDetectorRef } from '@angular/core';
  • 12. @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} // Example of lazy loading configuration import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; // Example using Renderer2 to set a class on an element import { Component, ElementRef, Renderer2 } from '@angular/core'; @Component({ selector: 'app-example', template: `Renderer2 Example` }) export class AppExample { constructor(private el: ElementRef, private renderer: Renderer2) { // Enabling AOT in Angular // Use the following command to build the application with AOT enabled ng build --aot const routes: Routes = [ { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) } ]; AOT also catches template errors during the build process, making debugging easier before deployment. Ans: Angular's Renderer2 service abstracts the DOM manipulation logic, allowing you to modify the DOM safely, even in environments where direct DOM access is not possible, such as server-side rendering or Web Workers. Ans: Lazy loading in Angular improves performance by loading modules only when they are needed. You can achieve this using the loadChildren property in the Angular Router configuration. Q.39 What is the role of Angular's Renderer2 service? Q.38 How can you implement lazy loading with Angular routes?
  • 13. @Injectable({ providedIn: 'root' }) export class GlobalService { getMessage() { } } return 'Service available globally'; @Component({ selector: 'app-example', template: `{{ data }}`, changeDetection: ChangeDetectionStrategy.OnPush }) export class AppExample { // Example of providing a service at the component level import { Injectable } from '@angular/core'; @Component({ selector: 'app-local', template: `{{ message }}`, providers: [LocalService] // Local service provided here }) export class LocalComponent { constructor(private localService: LocalService) { } } this.message = this.localService.getMessage(); } } this.renderer.setStyle(this.el.nativeElement, 'color', 'blue'); // Example of OnPush change detection import { Component, ChangeDetectionStrategy, Input } from '@angular/core'; Q.40 What is Angular's Dependency Injection (DI) hierarchy? Ans: Angular's DI hierarchy allows services to be provided at different levels, such as the root module, feature module, or component level. The hierarchical structure ensures that child components inherit services provided at a higher level unless explicitly overridden. Q.41 How do you optimize Angular applications for performance? Ans: Optimizing Angular applications involves several techniques, including: Using AOT compilation to reduce runtime overhead. Implementing lazy loading for modules. Using OnPush change detection for immutability. Minimizing the use of global variables and services.
  • 14. @Input() data: string; } @Component({ selector: 'app-form', template: `` }) export class FormComponent { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ // Example using FormBuilder import { Component } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; // Example of an Angular interceptor import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler): Observable> { const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') }); return next.handle(clonedRequest); } } Read More: Understanding Local and Global Variables in JavaScript Ans: Securing Angular applications involves: Using route guards like CanActivate to restrict unauthorized access. Securing API endpoints with tokens. Using Angular's DomSanitizer to prevent XSS attacks. Ans: Angular's FormBuilder simplifies the creation of reactive forms by reducing boilerplate code. It provides methods to create FormGroup and FormControl. Ans: Angular interceptors are used to modify HTTP requests or responses globally. They are implemented by creating a service that implements the HttpInterceptor interface. Q.43 How can you secure Angular applications? Q.44 How does Angular's FormBuilder simplify reactive forms? Q.42 What are Angular interceptors, and how are they implemented?
  • 15. } } name: [''] }); @Component({ selector: 'app-user', template: `User ID: {{ userId }}` }) export class UserComponent implements OnInit { userId: string; constructor(private route: ActivatedRoute) {} // Example of accessing route parameters import { ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { } } return !!localStorage.getItem('userToken'); // Example condition // Example of CanActivate route guard import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; ngOnInit() { } } this.userId = this.route.snapshot.paramMap.get('id'); // Accessing parameter using snapshot Q.45 How does Angular handle route guards? Ans: Angular route guards, like CanActivate, control navigation based on conditions, ensuring that only authorized users can access specific routes. Q.46 How does Angular handle routing with parameters? Ans: Angular routing allows you to pass parameters in the URL, which can be accessed in the component using the ActivatedRoute service. Parameters can be optional or required and can be accessed using snapshot or observable methods. Q.47 What is the difference between Template-Driven Forms and Reactive Forms in Angular? Ans: Angular provides two ways to build forms:
  • 16. Ans: The ngOnInit lifecycle hook is called once when the component is initialized, whereas ngAfterViewInit is called after the component's view has been fully initialized and rendered. Use ngOnInit for initialization logic and ngAfterViewInit for operations that require interaction with the view. Template-Driven Forms: Uses Angular directives like ngModel to bind form controls to data models. They are simpler but less scalable for complex forms. Reactive Forms:Angular Model-Driven (Reactive) Forms Provide more control and flexibility by using FormGroup and FormControl objects. Reactive forms are more scalable for larger forms. @Component({ selector: 'app-example', template: `` }) export class ExampleComponent { form: FormGroup; ngOnInit() { } this.message = 'ngOnInit called'; console.log('ngOnInit called'); constructor(private fb: FormBuilder) { } } this.form = this.fb.group({ name: [''] }); ngAfterViewInit() { this.message += ' and ngAfterViewInit called'; console.log('ngAfterViewInit called'); // Example of reactive form with FormBuilder import { Component } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; // Example showing ngOnInit and ngAfterViewInit lifecycle hooks import { Component, OnInit, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-lifecycle', template: `{{ message }}` }) export class LifecycleComponent implements OnInit, AfterViewInit { message: string; Q.48 What is the difference between Angular's ngOnInit and ngAfterViewInit lifecycle hooks?
  • 17. } } @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) {} // Example of an attribute directive import { Directive, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) { } } this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow'); canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { } } const isAuthenticated = !!localStorage.getItem('authToken'); // Check authentication status if (!isAuthenticated) { this.router.navigate(['/login']); return false; } return true; // Example of using route guards for authorization import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; Q.50 How do you implement authentication and authorization in Angular? Ans: Authentication and authorization in Angular can be handled using services that interact with a backend API for login and role validation. You can secure routes with route guards to restrict access based on user roles and authentication status. Common techniques include using JWT tokens for authentication. Q.49 What are Angular Directives, and how do they differ from Components? Ans: Angular directives are classes that allow you to manipulate the DOM in various ways, such as creating custom behavior or altering the appearance of elements. They are classified into three types: Structural Directives (e.g., *ngIf, *ngFor), Attribute Directives (e.g., ngClass, ngStyle), and Component Directives. Components are a type of directive with a template, while other directives do not have their own templates.
  • 18. Ans: Ans: Angular supports PWAs using the experiences using service workers. : Defines reusable HTML templates that are rendered dynamically. : Groups multiple elements without adding extra DOM nodes. Ans: NgRx is a reactive state management library for Angular. Implementation steps: Install NgRx: ng add @ngrx/store. Define actions, reducers, and selectors. Ans: Angular Universal enables SSR, improving SEO and performance. To implement SSR: Install Angular Universal: ng add @nguniversal/express-engine. Build the app: npm run build:ssr. Run the server: npm run serve:ssr. Ans: Angular handles memory leaks using automatic garbage collection. However, developers should follow best practices: Unsubscribe from Observables using takeUntil or async pipe. Detach event listeners to avoid reference leaks. Use ngOnDestroy() to clean up subscriptions. Limit DOM element manipulations and use trackBy in *ngFor. Ans: The trackBy function in *ngFor improves performance by preventing unnecessary DOM updates. Instead of re-rendering the entire list when data changes, it updates only the modified elements. Ans: Web Workers in Angular run JavaScript in the background, preventing UI blocking. They improve performance by handling heavy computations separately. Angular provides Web Workers using ng generate web-worker. Ans: Angular's ViewEncapsulation controls how styles are applied to components. It helps encapsulate styles within a component to avoid conflicts with global styles. Angular provides three types of encapsulation: Emulated (default): Uses scoped styles but allows inheritance. ShadowDom: Uses native shadow DOM for true encapsulation. None: Applies styles globally. JWT tokens are typically stored in localStorage or sessionStorage for client-side authentication, and the backend verifies the token before granting access to protected routes. package. PWAs provide offline support, faster loading, and app-like Q.53 What is the role of trackBy in Angular's *ngFor directive? Q.51 What is the purpose of the Angular ViewEncapsulation feature? Q.57 What is the purpose of ng-template and ng-container in Angular? Q.56 How does Angular handle progressive web applications (PWAs)? Q.58 How do you implement state management in Angular using NgRx? Q.52 How does Angular handle memory leaks, and how can they be prevented? Q.55 What are Web Workers in Angular, and how can they improve performance? Q.54 How do you implement a server-side rendering (SSR) with Angular Universal? ng-template ng-container @angular/pwa
  • 19. Use (a) Two-way data binding (b) Dependency Injection (c) Component-based architecture (d) All of the above View Answer ⬇ to dispatch and select state updates. Read More: Angular Interview Questions and Answers Ans: Secure authentication token handling involves: Storing tokens in HttpOnly cookies instead of localStorage. Using Interceptor to add tokens to API requests. Implementing expiration checks and auto-logout mechanisms. (a) AngularJS is based on JavaScript, while Angular is based on TypeScript (b) AngularJS uses controllers, while Angular uses components (c) Angular is faster and supports mobile development (d) All of the above View Answer ⬇ Ans: Standalone components simplify Angular development by removing the need for Faster loading with tree shaking. Easier code maintenance. Better modularization and reusability. . Benefits include: This article covers the Top 50 Infosys Angular Interview Questions for freshers, intermediates, and experienced candidates. It highlights key Angular concepts such as dependency injection, routing, Angular modules, change detection, and lazy loading. These questions are designed to test your understanding of Angular's core features and practical implementations, ensuring you're well-prepared for your Infosys interview. Detailed answers with examples are provided to help you grasp and apply Angular concepts efficiently. Whether you're new to Angular or preparing for an advanced role, this guide is a valuable resource for success. Enhance your skills with the Angular Certification Online Training from ScholarHat. Master Angular through hands-on projects and expert insights to accelerate your career growth! Store NgModule Q 3: What are Angular lifecycle hooks? Q 1: What are the key features of Angular? Q 2: What is the difference between AngularJS and Angular? Q.59 What are the benefits of using standalone components in Angular? Q.60 How can you handle authentication tokens securely in an Angular application? Summary Infosys Angular Interview Questions
  • 20. (a) Using Template-driven forms (b) Using Reactive forms (c) Both (a) and (b) (d) None of the above View Answer ⬇ (a) Functions that execute during the component lifecycle (b) A feature that speeds up Angular applications (c) Methods to manage API calls (d) A tool for debugging components View Answer ⬇ (a) To share data between components (b) To handle API calls (c) To implement business logic separately from components (d) All of the above View Answer ⬇ Q 5: What is the purpose of Angular Services? Q 4: How does Angular handle form validation?