Angular Interview Questions (Free Preview)
Free sample of 15 from 50 questions available
Angular Basics
What is Angular?
Angular is an open-source framework based on TypeScript for building web applications, developed and maintained by Google. The framework focuses on fast application development and simplifying the binding of components to data models. Key advantages of using Angular include:
- A dependency injection mechanism that simplifies application configuration,
- A dynamic templating system,
- Two-way data binding,
- Built-in functionalities that eliminate the need for additional libraries (e.g., routing, state management, RxJS, HTTP),
- Extensive availability of developer tools and third-party libraries.
Components
What is a Component?
A component is a class annotated with the @Component decorator that defines a segment of an application's user interface (UI). It consists of a directive that is associated with a template. Unlike other directives, only one component can be assigned to a single DOM element.
An application must have at least one root component, which links the component tree to the DOM model.
Every component must be part of an NgModule to be rendered. For this purpose, it must be added to the declarations array in the NgModule metadata.
The behavior of components can be managed through their lifecycle, which begins when Angular initializes the component and starts rendering it along with all its dependent components.
How Can Two Components Communicate?
In Angular, two components can communicate in several ways:
- Using the
@Input()decorator, a parent component can pass data to a child component. - Using the
@Output()decorator in conjunction with anEventEmitter, a child component can pass data to a parent component. - Using the
@ViewChild()decorator, a parent component can access data from a child component. - Through a shared service instance that is injected into both components.
- Via a shared
Subject<T>object.
Dependency Injection
How Does Dependency Injection Work?
The Dependency Injection mechanism is a design pattern where a class declares the dependencies it requires instead of creating them by itself. These required dependencies are then injected at the time the class's objects are instantiated.
In Angular, the mechanism consists of two parts:
- Injector – When Angular creates a component, service, or directive that needs dependencies (e.g., an external service), it first checks if the injector already has an instance of that service. If no instance exists, the injector uses the appropriate provider to create one.
- Provider – An object that contains information about how to obtain or create a dependency.
What Is Data Binding?
Data binding is a mechanism that connects the component’s state to the DOM model. In Angular, there are four forms of data binding:
- Text interpolation (
{{ }}) – allows you to render the values of variables from the component into the HTML. - Property binding (
[ ]) – links the state of HTML elements and directives with the component’s state; data flows from the component to the HTML element. - Event binding (
( )) – enables the component to react to user events (e.g., mouse movements, clicks, keypresses); data flows from the HTML element to the component. - Two-way data binding (
[()]) – a combination of property binding and event binding that ensures a synchronized state between the component and the view. This is implemented using thengModeldirective from the FormsModule.
Directives
What Are Directives Used For?
A directive is a class marked by the @Directive() decorator. When Angular renders a template, it modifies the DOM tree according to the instructions provided by the directives. They define how DOM elements should be added or modified.
Directives, similarly to components, have their own lifecycle, which can be leveraged to implement or configure their behavior.
There are two types of directives: structural and attribute directives.
You can also create custom directives using the @Directive() decorator.
The most commonly used directives include: ngFor, ngIf, ngModel, ngStyle, and ngClass.
Change Detection
How does the change detection mechanism work?
Change detection is the process of synchronizing the view with the data. In simplified terms, the process works as follows:
- Angular compares the current state of data with the previously stored state and collects all the changes.
- It invokes
ngOnInit,ngOnChanges, andngDoCheckon child components. - The component's DOM is updated to reflect changes in the model.
- Change detection is run on the child components.
- It calls
ngAfterViewIniton child components.
By default, change detection does not perform deep comparisons of complex objects. Only primitive values or object references are compared.
↑ Back to topWhat change detection strategies do you know?
Two change detection strategies are utilized:
ChangeDetectionStrategy.Default– This is the default CheckAlways strategy, where all components in the component tree (from the root down to the leaves) are checked for changes every time change detection runs.ChangeDetectionStrategy.OnPush– This is the CheckOnce strategy, where checking is only triggered on demand or when the reference to the object bound to the view changes; this helps avoid unnecessary checks of the component’s values and all its child components.
Component Lifecycle
What is a lifecycle hook?
A lifecycle hook is an interface that allows you to integrate with the lifecycle of a directive or component at the time it is created, updated, or destroyed. You can leverage a lifecycle hook to fetch data required to construct the component, manually trigger change detection, respond to changes in the component, or perform cleanup before its removal. Each stage of the lifecycle is represented by an interface that defines a single method corresponding to a specific hook. The method's name starts with ng, for instance, the OnInit interface includes a hook called ngOnInit(). There is no need to implement all lifecycle methods; you only implement those you use and need.
What Is the Difference Between ngOnInit and the Constructor?
The constructor is a class mechanism rather than an Angular-specific feature. Angular’s dependency injection system inspects the constructor’s parameter list and injects required dependencies. The constructor's primary role is to ensure that the class is initialized properly. It is generally advised not to include any component logic within the constructor; instead, such logic should be transferred to ngOnInit(). The method ngOnInit() is a lifecycle hook for the component or directive that Angular calls after the component’s properties have been set and the initial display has occurred. It is an ideal place to perform all initialization tasks that you would want to avoid in the constructor.
Reactive Programming
What Is the Difference Between an Observable and a Promise?
| Promise | Observable |
|---|---|
| Eager – executes immediately upon creation | Lazy – executes only when a subscriber appears |
Chaining is done via Promise.then() |
Chaining is done using RxJS operators |
| The processing cannot be stopped | Processing can be cancelled by calling unsubscribe() |
| Delivers only a single value | Delivers a stream of multiple values over extended time |
Pipes
What Is the Purpose of a Pipe?
A Pipe is a class that represents a simple function for formatting data within templates—for example, numbers, currencies, dates, or even complex objects. Pipes can accept parameters and be chained together to form a series of transformations as shown below:
{{ fund.launchDate | date:'fullDate' | uppercase }}
Angular includes a set of built-in pipe implementations, such as DatePipe, CurrencyPipe, and DecimalPipe. In addition, you can create your own custom pipes by implementing the PipeTransform interface:
@Pipe({name: 'courseDate'})
export class CourseDate implements PipeTransform {
transform(value: string) {
return moment(value)
.format('DD/MM/YY').toUpperCase();
}
}
↑ Back to top
Performance Optimization
How to Implement Lazy Loading?
Lazy loading is a design pattern that, in the context of Angular, allows you to load an NgModule only when it is required rather than loading all modules immediately upon startup.
To implement lazy loading, define the loadChildren property in your AppRoutingModule routing configuration as shown below:
const routes: Routes = [{
path: 'users',
loadChildren:
() => import('./users/users.module')
.then(m => m.UsersModule)
}];
In this example, the UsersModule is loaded lazily when the application navigates to the users path.
Testing
What is the purpose of TestBed?
TestBed is one of Angular's testing utilities.
It dynamically creates a new testing module that mimics an @NgModule. This testing module can be configured with metadata similarly to an @NgModule.
Using the inject() method, we can then inject a component or service that was created this way into the test:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
CourseListComponent,
{ provide: UserService, useClass: MockService }
]
});
component = TestBed.inject(CourseListComponent);
userService = TestBed.inject(UserService);
});
↑ Back to top
Security
What is the Purpose of an HTTP Interceptor?
An HTTP interceptor is a service that can modify the outgoing HTTP requests and incoming responses handled by Angular's HttpClient. It is typically used for logging HTTP requests and adding headers (e.g., for authentication purposes). The interceptor implements the HttpInterceptor interface and defines the intercept(req, next) method. For example:
@Injectable()
export class Logger implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
// Process the outgoing request (req) here...
const resp = next.handle(req);
// ... and optionally process the response (resp) here
return resp;
}
}
↑ Back to top