Tech Point Fundamentals

Saturday, February 3, 2024

Angular Interview Questions and Answers - Part 20

Angular Interview Questions and Answers - Part 20

Angular-Interview-Questions-And-Answers

Angular is a popular single-page application design framework and development platform. It is a robust open-source JavaScript framework that is widely used for front-end application development. Nowadays Angular is very common as frontend technology so it is very common for the interview point as well. 

Introduction


This is the Angular Interview Questions and Answers series. Here we will see 200+ Most Frequently Asked Angular Interview Questions. This is the 20th part of the Angular Interview Questions and Answer series.

I will highly recommend to please do visit the following parts before continuing to this part:



Please do visit our YouTube Channel here to watch Interview Questions & Answers and important technology videos.

In this part we will discuss the following Important Angular Interview Questions:

Q224. What are HttpInterceptors in Angular?
Q225. What is the use of HTTPInterceptors in Angular?
Q226. Can you add multiple interceptors in Angular? 
Q227. How can you register and use an interceptor for an entire application in Angular?
Q228. What is Change Detection in Angular? What is the disadvantage or limitation of the Change Detection in Angular?
Q229. What are the different ways to trigger the change detection in Angular?
Q230. What are the possible data update scenarios for change detection?
Q231. What is an Angular Router? What do you understand by the router imports?
Q232. Where and how can you define the routing in the Angular application?
Q233. What is the default order of the Route in Angular? Does route order matter in Angular?
Q234. What are router links in Angular?

Angular Interview Questions and Answers: Part 20


Q224. What are HttpInterceptors in Angular?

HttpInterceptors are a powerful feature of the Angular framework that allows you to intercept HTTP requests and responses. Intercepters sit between your application and the backend and can be used to modify the request or response before it is sent or received.

HttpInterceptors are part of the @angular/common/HTTP module and are used to inspect and transform HTTP requests and HTTP responses. Interceptors provide a way to modify or handle HTTP requests and responses at a centralized location before they reach the server or client.  These interceptors can perform a variety of implicit tasks.

These interceptors are created to perform checks on a request, manipulate the response, and perform cross-cutting concerns, such as logging requests, authenticating a user using a request, using gzip to compress the response, etc. We can update the value of the request by intercepting the HTTP request, and we can perform some specified actions on a specific status code or message by intercepting the answer.

This can be useful for logging requests, adding authentication headers, handling errors, or modifying request/response data. Interceptors can be registered in the Angular module and are executed in a specific order based on the request/response pipeline.

To create an HttpInterceptor, you need to implement the HttpInterceptor interface provided by the @angular/common/http package. The interface contains a single method intercept with the following signature:

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

The intercept method takes two arguments: req and next. The req argument is an instance of the HttpRequest class, which represents the outgoing HTTP request. The next argument is an instance of the HttpHandler class, which represents the next interceptor in the chain or the final destination for the request.

You can use interceptors by declaring a service class that implements the intercept() method of the HttpInterceptor interface.

import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';

@Injectable()
  export class CustomHeaderInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
    const modifiedReq = req.clone({
      headers: req.headers.set('X-Custom-Header', 'custom-value')
    });
    return next.handle(modifiedReq);
    }
  }

After that, you can use it in your module. You have to register the interceptor as singleton in the module providers:

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { CustomHeaderInterceptor } from './http-interceptors.service';

@NgModule({
declarations: [],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomHeaderInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Q225. What is the use of HTTPInterceptors in Angular?

Using the HttpClient, interceptors allow us to intercept incoming and outgoing HTTP requests. They are capable of handling both HttpRequest and HttpResponse. We can edit or update the value of the request by intercepting the HTTP request, and we can perform some specified actions on a specific status code or message by intercepting the answer.

Interceptors provide a way to modify or handle HTTP requests and responses at a centralized location before they reach the server or client. These interceptors can perform a variety of implicit tasks:

  1. Authentication
  2. Logging
  3. Caching
  4. Fake backend
  5. URL Transformation
  6. Modifying headers
  7. Handle Errors

Interceptors can be registered in the Angular module and are executed in a specific order based on the request/response pipeline.

Q226. Can you add multiple interceptors in Angular? 

Yes, Angular supports multiple interceptors at a time. 

Interceptors can be registered in the Angular module and are executed in a specific order based on the request/response pipeline. You could define multiple interceptors in providers property of ngModule:

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: CustomHeaderInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }
  ]

The interceptors will be called in the same order in which they were provided. i.e., CustomHeaderInterceptor will be called first in the above interceptors configuration.

Q227. How can you register and use an interceptor for an entire application in Angular?

You can use the same instance of HttpInterceptors for the entire application by importing the HttpClientModule only in your root AppModule and adding the interceptors to the root application injector. 

  • Create a service that implements the HttpInterceptor interface.
  • Implement the intercept() logic in the service to modify the HTTP requests and responses based on your requirements.
  • Now import the HttpClientModule in your application’s root module.
  • Add the interceptor to the root module application injector by providing it in the HTTP_INTERCEPTORS multi-provider array.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { InterceptorComponent } from './interceptor/interceptor.component';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { CustomHeaderInterceptor } from './http-interceptors.service';

@NgModule({
  declarations: [
    AppComponent,   
    InterceptorComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CustomHeaderInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the above example, we have registered the CustomHeaderInterceptor in the root module.

Q228. What is Change Detection in Angular? What is the disadvantage or limitation of the Change Detection in Angular?

The process of synchronizing a model with a view is known as Change Detection. Change Detection is a mechanism in Angular that checks whether the application state has changed and updates the view accordingly. It is the process through which Angular detects changes in the application’s data model and updates the view to reflect those changes.

Change Detection Process in Angular:

Change Detection is the mechanism that determines when and how to update the user interface based on changes in the application's data model. Angular uses a tree of change detectors to track changes in component properties and update the DOM accordingly. 

When a change occurs, Angular performs a process called change detection, which involves checking each component's properties for changes and updating the DOM if necessary. The change detection mechanism is responsible for keeping the UI in sync with the application's data.

Disadvantage of Change Detection Mechanism:

Angular walks your components from top to bottom, looking for changes, and runs its change detection mechanism periodically so that changes to the data model are reflected in an application’s view. Change detection can be triggered either manually or through an asynchronous event.

To avoid performance issues, Angular’s change detection mechanism is highly optimized and performant. However, it can still cause slowdowns if the application runs it too frequently.

Change Detection Mechanism moves forward only and never backward, beginning with the root component and ending with the last component. This is what one-way data flow entails. 

Even when using the ngModel to implement two-way binding, which is syntactic sugar on top of a unidirectional flow, change detection is incredibly fast, but as an app's complexity and the number of components increase, change detection will have to do more and more work.

Q229. What are the different ways to trigger the change detection in Angular?

There are multiple ways to trigger change detection in Angular:

1. Manually: 

You can manually trigger change detection by calling the detectChanges() method of the ChangeDetectorRef object. This method checks the current component and its children for changes and updates the view accordingly. It detects only the components and it's children.

2. Asynchronously: 

Angular’s change detection mechanism can be triggered asynchronously through an event such as a user interaction or an XMLHttpRequest completion. You can use the NgZone service to run a callback function inside the Angular zone, which will automatically trigger change detection for the entire application. It evaluates the callback function inside the Angular zone.

3. Periodically: 

Angular periodically runs its change detection mechanism to check for changes in the application’s data model and update the view accordingly. You can control how often this mechanism runs by using the ChangeDetectionStrategy class and setting its OnPush mode.

ApplicationRef.tick():  Invoke this method to explicitly process change detection and its side effects. It checks the full component tree.

Q230. What are the possible data update scenarios for change detection?

The change detection works in scenarios where the data changes need to update the application HTML. Several scenarios can trigger data updates in Angular’s change detection mechanism:

1. Component Initialization: While bootstrapping the Angular application, Angular triggers the ApplicationRef.tick() to call change detection and View Rendering.

2. DOM EventListener: The DOM event listener can update the data in an Angular component and trigger the change detection too.

3. User Events: User interactions such as button clicks, form submissions, and mouse movements can trigger data updates. Apart from this Custom events can be used to trigger data updates in specific components or services.

4. HTTP Data Request: You can get data from a server through an HTTP request. Data returned from HTTP requests can trigger data updates.

5. WebSockets and Canvas: Data received from WebSockets can also trigger data updates. The data can be updated asynchronously using WebSocket.onmessage() and Canvas.toBlob().

6. Timers and Intervals: Timers and intervals can trigger data updates at regular intervals. Macro tasks setTimeout() or setInterval() can update the data in the callback function of setTimeout or setInterval.

7. Asynchronous Operations: Asynchronous operations such as Promises and Observables can trigger data updates when they are complete.

8. Third-Party Libraries: Third-party libraries such as D3.js and Google Maps can trigger data updates.

Q231. What is an Angular Router? What do you understand by the router imports?

Angular Router is a powerful and flexible navigation library that allows you to manage the navigation and URLs of the Angular application. It allows us to define routes, which are URL patterns that map to specific components, and navigate between those routes.

Angular Router:

Routing in a single-page application (SPA) is the task of responding to the changes in the URL made by adding and removing content from the application. An Angular Router is a mechanism in which navigation happens from one view to the next as users perform application tasks. It borrows the concepts or model of the browser's application navigation. It enables developers to build single-page applications with multiple views and allows navigation between these views.

The Angular Router which represents a particular component view for a given URL is not part of Angular Core. It is available in the library named @angular/router to import required router components.  

Router Import:

To use the Angular Router, you need to import the RouterModule and Routes classes from the @angular/router package. You can then define your routes using the Routes class and configure them using the RouterModule.forRoot() method. The RouterModule.forRoot() method is a pattern used to register application-wide singleton providers.

A router must be configured with a list of route definitions. Each definition translates to a Route object which has two things: a path (URL path segment for this route) and a component, i.e. component associated with this route.

The router draws upon its registry of definitions when the browser URL changes or when the application code tells the router to navigate along a route path.

Q232. Where and how can you define the routing in the Angular application?

To handle the navigation from one view to the next, you use the Angular Router. The Router enables navigation by interpreting a browser URL as an instruction to change the view.

We can define routes in the AppRoutingModule module i.e. app-routing.module.ts file, which is an NgModule where you can configure your routes. It is asked by the CLI when you are creating the Angular applicatin by ng create new command whether routing should be generated or not. 

ng new routing-app --routing --defaults

To use the Angular router, an application needs to have at least two components so that it can navigate from one to the other.  To create a new route, you need to import the RouterModule and Routes classes from the @angular/router package and define your routes using the Routes class. 

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserComponent } from './user/user.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: 'User', component: UserComponent },
  { path: '', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Here we defined a single route that maps to the HomeComponent when the URL is empty. You can also use route parameters to pass data between components and use guards to protect routes from unauthorized access.

Now you can add your routes to your application.  Assign the anchor tag that you want to add the route to the routerLink attribute. Set the value of the attribute to the component to show when a user clicks on each link.
Next, update your component template to include <router-outlet>. This element informs Angular to update the application view with the component for the selected route.

<nav>
  <ul>
    <li><a routerLink="/home-component" routerLinkActive="active" ariaCurrentWhenActive="page">HOME </a></li>
    <li><a routerLink="/user-component" routerLinkActive="active" ariaCurrentWhenActive="page">USER</a></li>
  </ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>

Q233. What is the default order of the Route in Angular? Does route order matter in Angular?

The order of routes is important because the Router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes.

It is recommended to list routes with a static path first, followed by an empty path route, which matches the default route. 

If you have a wildcard route, it should always be the last route in your array.  The wildcard route comes last because it matches every URL and the Router selects it only if no other routes match first.

Q234. What are router links in Angular?

Router links are a built-in Angular directive that allows you to create links to specific routes in your application. They are used to navigate between different views in your application without reloading the page.

RouterLink is an anchor tag directive that gives the router authority over those elements. The RouterLink is a directive on the anchor tags that give the router control over those elements. Router links in Angular are used for navigation within an application.

Router links can be used in HTML templates and are typically placed on anchor (<a>) tags or other clickable elements. By specifying the destination route or component, router links allow users to navigate between different parts of an Angular application.

To use router links, you need to import the RouterModule and Routes classes from the @angular/router package. You can then define your routes using the Routes class and configure them using the RouterModule.forRoot() method.

<nav>
  <ul>
    <li><a routerLink="/home-component" routerLinkActive="active" ariaCurrentWhenActive="page">HOME </a></li>
    <li><a routerLink="/user-component" routerLinkActive="active" ariaCurrentWhenActive="page">USER</a></li>
  </ul>
</nav>





Recommended Articles




Thanks for visiting this page. Please follow and join us on  LinkedInFacebookTelegramQuoraYouTubeTwitterInstagramWhatsApp, VKTumbler, and Pinterest for regular updates.

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.