circuit

Advanced Angular Interview Questions You Must Prepare For in 2022

Latest Angular Interview Questions




Photo by Andrew Neel on Unsplash

Photo by Andrew Neel on Unsplash

Recently, I was trying to prepare myself for the upcoming interviews and it was a bit tough to search in Google, open the links and see the same questions each and every time. So, I thought of sharing what I have found and what the most common questions are that someone should know if they are preparing for an interview.

Below are the most common interview questions asked in the latest Angular developer interviews. These Angular Interview questions and answers help to prepare for Angular developer interviews from junior to senior levels. Moreover, this article covers the basics to advance Angular interview questions which you must prepare for in 2022.

I also updated the questions which I mostly ask during any frontend developer jobs.

Let's start with some basic questions:

1. What is the difference between constructor and ngOnInit?

One of the common questions which pop up in the interviewer's mind is what is the difference between constructor and ngOnInit? We mostly go with the answer that we write the dependencies in the constructors while we write logics in the ngOninit.

Sometimes, the interviewer will check what else we know about it? Why can't we put the services or logics in constructors?

The simple answer is that sometimes, we need to wait until all dependencies get loaded; or for parent/child components, we might need to wait until the component is loaded. That's why it's preferable to write the logic in ngOnInit.

Let's check other differences.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/ngoninit-vs-constructor

2. What is the difference between components and directives?

This one is extremely common too. The easy answer is directives do not have their shadow DOM while components have their HTML. Components used to break our application based on features, while directives only help to change the behavior of certain elements.

Let's check out some other differences.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-directive

3. What is the difference between ElementRef, TemplateRef, and viewContainerRef?

This question comes for more advanced Angular interviews where the interviewer wants to check how you are manipulating views or do you have experience in creating dynamic views in your Angular application.

Let's check out the difference between ElementRef, TemplateRef, and viewContainterRef with examples.

ElementRef Example:

TemplateRef Example:

ViewContainerRef Example:

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/elementref-templateref-viewcontainerref

4. What is the difference between ng-content,ng-template, and ng-container?

Doesn't it look the same? Yes, when I was learning Angular all 3 keywords were the same for me but actually, all carry their own purposes.

Let's check out the difference between ng-content,ng-template, and ng-container with examples.

ng-content example:

ng-template example:

ng-container example:

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-ng-template-ng-content-ng-container-example

5. What is the difference between view-child and content-child?

We do deal with a lot of parent-child or sub-components. As Angular does support creating dynamic component on the fly or access the relative components based on their relation interviewer expect that we know the difference between view-child and content-child.

Let's check the difference between view-child and content-child with the examples.

View-Child Example:

Content-Child Example:

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angulr-view-content-child

6. What is the difference between component view, host view, and embedded view?

This is an advanced Angular interview question that can be asked to know how the different views work in Angular.

Let's check the difference between component view, host-view, and embedded views with the examples.

Embedded View Example:

Host View Example:

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/ng-embedded-view

7. What is the difference between debounce time and throttle time?

When we deal with the reactive forms and want the user to type and check on service based on the inputs this two-term is very handy.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/throttletimevsdebouncetime

8. What is the difference between forEach and map?

Let's discuss the basic JavaScript interview question. Sometimes interviewer asks when we can use forEach and map and what are the differences between them.

Let's check out the difference between forEach and map.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/ken-demo-foreach-vs-map

9. What is the difference between ng-content and ng-templateoutlet?

When we deal with multiple templates it is better to write reusable logic in the template itself. Having knowledge of these two terms can boost your chance to crack the Angular developer interviews.

ng-content Example:

ng-templateoutlet example:

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/ngtemplateoutlet-and-content-projection

https://stackblitz.com/edit/ng-content-demo-example

10. What is the difference between forchild vs forroot?

This is a bit advanced topic but the basic difference is by using forchild and forroot we can change the visibility of instances of service in the application.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/4-forroot-vs-forchild-with-forroot-and-forchild

11. Why we use pipe operators in RXJS. What is the use of it?

The pipe() method helps to write multiple rxjs functions together and it combines everything.

for example:

of(1,2,3).pipe(
 map(x => x + 1),
 filter(x => x > 2)
);
  1. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

  2. we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/rxjs-pipe

12. What is the difference between using the Async pipe vs the subscribe function in the Angular application?

We do use Async pipe and subscribe function a lot in our application but what are the basic difference between them and why we do use one then other?

Let's check it out.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/component-vs-async-pipe-subscriptions-angular

13. What is the difference between promise and observable?

We do deal with both of the keywords lots but when should we use promise and observable? If we know the difference between promises and observables it will help us out to understand.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/observable-vs-promises

14. What is the difference between Event Emitter and Subjects?

We do use EventEmitter when we want to communicate child to parent components while subjects can be used when we want to communicate between un-relational components.

Below are two differences between them.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-subject-vs-event-emitter

15. What is the difference between Observable and Subject?

This is one of the common questions asked in the Angular interviews. Let's understand the difference between Observable and Subject.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/observables-and-subjects

16. What is the difference between Activated Route vs Activated route Snapshot?

The major difference between Activated Route vs Activated Route Snapshot is with Activated Route we can subscribe to Observable while Activated Route Snapshot only emits one value.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-router-snapshot-and-params-yakov

17. Discuss a different kind of loading strategies used in your Angular application

This kind of question is asked to check how deep you have used Angular. Most of the times we answer lazy loading and eager loading but there is one more in the list which we should consider...

Eager Loading

Feature modules under Eager Loading would be loaded before the application starts. This is the default module-loading strategy.

https://stackblitz.com/edit/ang-eager-loading-example

Lazy Loading

Feature modules under Lazy Loading would be loaded on-demand after the application starts. It helps to start the application faster.

https://stackblitz.com/edit/angular6-lazy-loading

Pre-Loading

Feature Modules under Pre-Loading would be loaded automatically after the application starts.

https://stackblitz.com/edit/angular-custom-preloading-strategy

Let's Continue with more questions.

18. What is Metadata?

Have heard about this word? We do use this daily meta in form of the class decorator or property decorator or other ways.

Let's see the definition of Metadata.

Metadata is used to decorate a class so that it can be configured the expected behavior of a class.

Below are the examples of metadata used in Angular.

  1. Class Decorator— @component

  2. Property Decorator— @Input

  3. Method Decorator— @HostListner

  4. Parameter Decorator— @Inject

19. What is routerlinkActive use for?

This is the most commonly used directive when we do use navbar in our application. When we want to write CSS based on the active tab routerlinkActive is checked with boolean conditions.

The RouterLinkActive is a directive for adding or removing classes from an HTML element that is bound to a RouterLink. Using this directive, we can toggle CSS classes for active Router Links based on the current RouterState. The main use case of this directive is to highlight which route is currently active.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-routerlinkactive

20. Where we use generics in Angular?

This is one of the latest interview questions in Angular. Interviewers want to check how good you are writing clean by typecasting objects or specific Observable or Events.

There are different places where we commonly use generics.

  1. While defining emitters

    Output() click : EventEmitter = new EventEmitter ()

  2. While capturing the response from observable

    data: Observable

  3. Defining Interfaces

    interface Item { info:string, … } Input public items: Item[]

21. What is the wild card route?

One of the common use wild card route redirects to this route if someone types something which is not the proper path.

If the requested route URL does not belong to what's mentioned in the code, we get an error in the console.

So to avoid this error, and instead tell the user that the route doesn't exist, we use WILDCARD ROUTES.

Example:

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-feature-modules-final-and-wildcard-route-example

22. What is the difference between ngIf and hidden?

Isn't it both same? both have the same function of hiding the things.No, but if you check that ngIf won't load template if conditions get false while hidden will load the template and hide it.

ngIf will comment on the data if the expression is false. This way the data are not even loaded, causing HTML to load faster.

[hidden] will load the data and mark them with the hidden HTML attribute. This way data are loaded even if they are not visible.

So [hidden] is better used when we want the show/hide status to change frequently, for example on a button click event, so we do not have to load the data every time the button is clicked, just changing its hidden attribute would be enough.

23. What is a router outlet?

We do see this tag in the main app component HTML. But what is it? Let's understand this term.

The router-outlet is a directive that's available from the @angular/router package and is used by the router to mark wherein a template, a matched component should be inserted.

Thanks to the router outlet, your app will have multiple views/pages and the app template acts as a shell of your application. Any element, you add to the shell will be rendered in each view, only the part marked by the router outlet will be changed between views.

24. What is the Router state?

As the term defined router state maintains the state of the routes and can be accessed by subscribing to specific route events.

Let's understand in a detailed manner.

RouterState and ActivatedRoute are similar to their snapshot counterparts except that they expose all the values as observables, which are great for dealing with values changing over time.

Any component instantiated by the router can inject its ActivatedRoute.

If we navigate from “/inbox/33/messages/44” to “/inbox/33/messages/45”, the data observable will emit a new set of data with the new message object, and the component will display Message 45.

Accessing Snapshots

The router exposes parameters and data as observables, which is convenient most of the time, but not always. Sometimes what we want is a snapshot of the state that we can examine at once.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-routerlink-state

25. What is an Active route?

ActivatedRoute provides access to the URL, params, data, queryParams, and fragment observables.

URL changes are the source of any changes in a route. And it has to be this way as the user has the ability to modify the location directly.

Any time the URL changes, the router derives a new set of parameters from it: the router takes the positional parameters (e.g., ‘: id') of the matched URL segments and the matrix parameters of the last matched URL segment and combines those. This operation is pure: the URL has to change for the parameters to change. Or in other words, the same URL will always result in the same set of parameters.

Next, the router invokes the route's data resolvers and combines the result with the provided static data.

Given the following:

And navigating first to “/inbox/33/data/44” and then to “/inbox/33/data/45”, we will see:

url [{path: ‘data', params: {}}, {path: ‘44', params: {}}]
url [{path: ‘data', params: {}}, {path: ‘45', params: {}}]

26. Explain different injections in Angular.

One of the common interview questions asked in Angular interview questions is how you are using injections in Angular application?

There are 5 different ways we Angular provide dependency injections

  1. use class

  2. use value

  3. use factory

  4. token factory

  5. component injections

You can check out the Angular documentation for detailed explanations.

https://stackblitz.com/angular/pmmpqkbmanl

27. What is the best way to implement translations in Angular?

In the Single Page Application, One of the main features is multi-language support on the fly. But Sometimes the interviewer asks have you implemented translations in your application?

The most common library used for this is ngx-translate which provides a translation by adding in the JSON.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/ngx-translate-example

Let's Continue with more questions.

28. Explain different routing params in Angular.

We do use routing parameters to maintain the data or sometimes pass data when navigating from one route to another route.

Angular does support the following routing parameters.

  1. Required Parameters

  2. Optional Parameters

  3. Query Parameters

  4. NavigationExtras

29. What is a virtual scroll in Angular?

Here Interviewer wants to check if you have updated knowledge of the latest Angular features.

The central concept behind virtual rendering is rendering only visible items.

For example, if there are thousands of alerts in an application, an efficient way would be to load only the elements that are visible and unload them when they are not by replacing them with new ones.

An initial implementation of virtual scrolling is now available in @angular/cdk. (v7.0.0-beta.0)

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/angular-virtual-scrolling

30. What is the difference between route param vs query param?

The key difference between query parameters and route parameters is that the route parameter is essential to determining the route, whereas query parameters are optional.

Let's understand some of the basics of Routing in Angular.

Declaring Route Parameters

The route for the component that displays the details for a specific product would need a route parameter for the ID of that product. We could implement this using the following Routes:

export const routes: Routes = [

{ path: '', redirectTo: 'data', pathMatch: 'full' },

{ path: 'data', component: DataList },

{ path: 'data/:id', component: DataDetails }

];

Note :id in the path of the product-details route, which places the parameter in the path. For example, to see the product details page for a product with ID 5, you must use the following URL: localhost:3000/product-details/5.

Passing Query Parameters

Use the [queryParams] directive along with [routerLink] to pass query parameters. For example:

<a [routerLink]="['data-list']" [queryParams]="{ page: 99 }">Go to Page 99</a>

Alternatively, we can navigate programmatically using the Router service:

goToPage(pageNum) {

this.router.navigate(['/data-list'], { queryParams: { page: pageNum } });

}

31. Explain different guards supported in Angular.

This is one of the most common questions asked in the Angular application.

There are five main guards in Angular. which guards the access of routes.

  • CanActivate: will be called before going to the route: can be used to prevent routing to a specific path

  • CanActivateChild: will be called before going to the child component: can be used to prevent the loading of child path

  • CanDeactivate: will be called before destroying the component: can be used to handle the browser events

  • CanLoad: will be called before loading the module: can be used to prevent the loading of the module

  • Resolve: will be called before loading component: can be used to prefetch data before loading component

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/route-guard

32. What is the best way too lazy load the component?

Lazy loading the modules is one of the best practices when we want to reduce the bundle sizes and avoid loading all modules together.

But What about the lazy loading component? It means we load modules but don't load components until we need them. It basically creates dynamic components as required and destroying right after use.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/ivy-lazy-loading-component

33. What is the way we can display the app version in Angular?

When we deal with a lot of deployment it is best to display the app version which helps to communicate among the team with the changes.

It can be achieved by following these steps.

  1. In your /tsconfig.json (sometimes also necessary in /src/tsconfig.app.json) enable the resolveJsonModule option (webpack dev server restart required afterward):

    "compilerOptions": { ... "resolveJsonModule": true ...

  2. Then in your component, for example /src/app/app.component.ts use the version info:

    import { version } from '../../package.json'; ... export class AppComponent { public version: string = version;

    }

It's also possible to do step 2 in your environment.ts file, making the version info accessible from there.

34. What are the generators in ES6?

Generator functions can pause and be resumed one or multiple times, which makes them interesting and very different from normal functions. While the function is paused, it allows other functions and code to execute. By default, generators are asynchronous.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/es6-generators

35. Explain the Error mechanism in your application.

All the application have their global error mechanism to handle the errors and log them on Splunk or new relic. Most of the team follow the global error mechanism which logs if any issues come for tracking purposes and redirect the users to specific routes.

Let's check out some practical code to understand this concept better.

https://stackblitz.com/edit/global-error-handler

36. What is bootstrapping in Angular?

Most of the time when this word comes to mind we think like a bootstrap library but no Bootstrapping is a technique of initializing or loading our Angular application.

Sometimes interviewers ask How Angular application loads or explain Angular application loading from the beginning. Let's check the answer then.

The Angular takes the following steps to load our first view.

  1. Main.ts the application entry point

  2. Index.html loads

  3. Angular, Third-party libraries & Application loads

  4. App Module

  5. App Component

  6. app-root will add the component HTML inside

To know in detail see below.

https://www.tektutorialshub.com/angular/angular-bootstrapping-application/#:~:text=Bootstrapping%20is%20a%20technique%20of,to%20load%20our%20first%20view.

37. What are Angular elements? why we use it?

As Angular grows it comes with really good features. If you heard about microservices architecture to make applications more robust Angular is doing exactly the same.

With Angular Elements, we can plug and play Angular applications to the other frontend frameworks.

With the release of Angular 6, the new Angular Elements functionality is now fully available. By using Angular Elements you can package Angular components as custom elements, a web standard for defining new HTML elements in a framework-agnostic way.

Let's Continue with more questions.

38. What is the difference between the arrow function and regular functions?

I have seen the interviewer started asking basic JavaScript questions to test the knowledge of candidates.

Candidate: I do know arrow functions have simpler syntax while regular functions have complex syntax.

The interviewer mostly understand how much deep water is :)

Answer:

1. Argument Binding:

Arrow functions do not support an arguments binding while regular functions do have the support of argument binding (however, we can add arguments in arrow functions using spread operator).

2. This keyword:

Arrow functions do not support this keyword while regular function has its own keyword support. This feature makes regular functions usage towards the factory method for object creation.

3. New keyword:

Regular functions created using function declarations are construable and can be called using the new keyword. However, the arrow functions are only callable and not construable, i.e arrow functions can never be used as constructor functions.

4. Duplicate Parameters:

Regular functions allowed duplicate parameters while Arrow functions don't allow duplicate parameters.

39. What is the difference between Functional vs Object Oriented Programming language? Which one you prefer and why?

I have seen a couple of interviewers started asking this kind of question to access candidate knowledge about the programming language they are currently working on.

geeksforgeeks

geeksforgeeks

The Advantages and Features of Functional programmings are:

  • Pure functions

  • Function composition

  • Avoid shared state

  • Avoid mutating state

  • Provide Higher-Order Functions

40. What is the difference between JavaScript and TypeScript?

Candidate: TypeScript is a superset of JavaScript.

I have seen most of the candidate's answers plain as they don't know many advantages of why Angular uses the TypeScript.

  • TypeScript is known as an Object-oriented programming language whereas JavaScript is a scripting language.

  • TypeScript has a feature of Static typing while JavaScript does not have this feature.

  • TypeScript gives support for modules whereas JavaScript does not support modules.

  • TypeScript supports Interface but JavaScript does not support Interface.

  • TypeScript support optional parameter in the methods but JavaScript does not support optional parameter in methods.

Advantages of using TypeScript over JavaScript

  • TypeScript always give compilation errors at run time due to this it is easier to fix the issue before deployments

  • TypeScript supports static typing which allows for checking type correctness at compile time.

41. What do you know about Closures?

A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Practically if we want to make any variable private which should not be accessible by any functions we can use closures.

Below is the Simple example I found from stack overflow.

Suppose, you want to count the number of times a user clicked a button on a website. For this, we are triggering a function on onClick event of the button to update the count of the variable

<button onclick="updateClickCount()">click</button>

Now there could be many approaches like:

  1. You could use a global variable, and a function to increase the counter:

    var counter = 0;

    function updateClickCount() { ++counter; // do something with counter }

But, the pitfall is that any script on the page can change the counter, without calling updateClickCount().

  1. Now, You might be thinking of declaring the variable inside the function:

    function updateClickCount() { var counter = 0; ++counter; // do something with counter }

But, Hey! Every time updateClickCount() function is called, the counter is set to 1 again.

  1. Thinking about Nested functions?

Nested functions have access to the scope “above” them. In this example, the inner function updateClickCount() has access to the counter variable in the parent function countWrapper().

function countWrapper() {
    var counter = 0;
    function updateClickCount() {
    ++counter;
    // do something with counter
    }
    updateClickCount();
    return counter;
}

This could have solved the counter dilemma if you could reach the updateClickCount() function from the outside and you also need to find a way to execute counter = 0 only once not every time.

  1. Closure to the rescue! (self-invoking function):

    var updateClickCount=(function(){
     var counter=0;
    
    return function(){
       ++counter;
       // do something with counter
        }
    })();
    

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way updateClickCount becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have “private” variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the add function!

Let's move towards the Angular Questions:

42. What is the difference between Template Driven forms and Reactive Forms?

43. What are different Kinds of Bindings possible in Angular?

One-Way Data Binding

  1. Interpolation Binding: It is a binding variable in HTML elements by adding curly brackets like

    {{value}}.

2. Property Binding: It is a binding specific property that is declared in the component.

<button [disabled]= “isDisabled” >

3. Attribute Binding: Attribute binding is used to bind an attribute property of a view element.

<td [attr.colspan]= “val”></td>

4. Class Binding: With the use of this binding method, we can add CSS classes conditionally to an element, creating dynamically styled elements.

<td class= “td” [class.red]= “val.age < 40">{{val.name}}</td>

5. Style Binding: it is the same as class binding providing specific style bindings.

<h1 [style.color]=”red”>Red</h1>

Two-Way Data Binding

This binding provides bidirectional communication between the component and the HTML.

<input [(ngModel)] ='val'>

Event Binding

This binding allows binding to an event.

(click)=”myClickFunction($event)”

Let's Continue with more questions.

45. Which RXJS Operators you use mostly to handle HTTP services?

Below are the Most Commonly used RXJS Operators to handle HTTP Services in Angular.

SUBSCRIBE: subscribe is used to get the data from the observable.

const data$ = this.service.getData(id);

data$.subscribe((response:IResponse) => console.log(response));

CATCH ERROR: Catch Error operator is used to handling errors, returning observable with error messages as below.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const data$ = this.service.getData(id);

data$.pipe(catchError(error => of (`error occured: ${error}`))).subscribe((response:IResponse) => console.log(response));

COMBINE LATEST

Combine Latest operator is used to emit only the latest values from multiple observable sources.

It is used when we are trying to make multiple API calls. Note: combinelatest will not emit an initial value until each observable emits at least one value.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

initializeDetails(id: string): void {
    combineLatest([
            this.service.getInitData(),
            this.service.getDetails(id),
        ])
        .pipe(
            catchError((error: HttpErrorResponse) => {
                return throwError(error);
            }),
            finalize(() => ),
            takeUntil(this._ngUnsubscribe$),
        )
        .subscribe(() => {});
}

To see running examples check out this stackblitz:

https://stackblitz.com/edit/angular-rxjs-combinelatest

DEBOUNCE TIME & DISTINCT UNTIL CHANGED

These operators are a perfect choice in scenarios such as type-ahead where the rate of user input must be controlled.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const inputValue = document.querySelector('input');
const dataObservable$ = fromEvent(inputValue, 'input');
dataObservable$.pipe(
        map(event => event.target.value),
        debounceTime(2000),
        distinctUntilChanged())
    .subscribe((data) => console.log(data));

You can check out the practical example here.

https://stackblitz.com/edit/rxjs-debouncetime-distinctuntilchanged

TAP

Tap operator is more of a utility operator that can be used to perform transparent actions such as logging.

const dataObservable$ = of (8, 9, 10, 11, 12);
dataObservable$.pipe(
    tap(val => console.log(`BEFORE MAP DATA: ${val}`)),
    map(val => val + 20),
    tap(val => console.log(`AFTER MAP DATA: ${val}`))
).subscribe(data => console.log(data));

You can check the practical example here:

https://stackblitz.com/edit/rxjs-tap-take

SWITCH MAP

One of the major issues with the callbacks or promises that it is really tough for us to cancel the request in middle.

For example, if you watching some video and right after a few seconds you thought of changing to a new video.. at this time we were still waiting for previous video requests and new requests came up. How we can cancel that request? Is this possible?

Yes, SwitchMap makes it possible.

SwitchMap operator provides an easy mechanism to cancel these network requests. For example, look at the below code using the switchMap operator.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const obs$1 = fromEvent(document, 'click');
const obs$2 = interval(1000);
const finalObs$ = obs$1.pipe(
    switchMap(event => obs$2)
);
const subscription = finalObs$.subscribe((value) => console.log(value));

You can check the practical example here:

https://stackblitz.com/edit/switchmap-syp5b1

FORK JOIN

It is used to combine multiple observables and make them in a stream.

It will wait for all observables to complete and then it will emit an array so it is useful to wait for all HTTP services provides a response.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const service1 = http.get < Data1[] > (this.data1);
const service2 = http.get < Data2[] > (this.data2);

forkJoin([service1, service2])
    .subscribe(res => {
        this.data = res;
        console.log('Stream Data', res);
    });
}

You can play with the practical example here:

https://stackblitz.com/edit/angular-rxjs-forkjoin-example

RETRY

If the service returns an error this method will resubscribe to the source Observable for a maximum count written in the parameter.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

this.authService.getData()
  .pipe(
     retry(3), // you retry 3 times
     delay(1000) // each retry will start after 1 second,
  )
  .subscribe(res => {
     // success
  })

retry can be used in the interceptor to retry the HTTP service calls after failure. You can check out the practical example of retry here:

https://stackblitz.com/edit/angular-dcv7vw

46. Which RXJS operators used for transforming or manipulating data?

Below are the most commonly used RXJS operators for transforming data.

MAP

the map works the same as the JavaScript map function. It is mostly used to transform the response to the new array.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const data = [{
 id: 1,
 value: ‘one'
}, {
 id: 2,
 value: ‘two'
}, {
 id: 3,
 value: ‘three'
}];

const dataObservable$ = from(data).pipe(
 map(data => data.value)
).subscribe(x => console.log(x));

REDUCE

Reduces the values from the source observable to a single value that's emitted when the source completes.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const data = of(1, 2, 3, 4);

const sum = data.pipe(reduce((acc, val) => acc + val));

//output: Sum: 10

const subscribe = sum.subscribe(val => console.log('Sum:', val));

TOARRAY

Collects all source emissions and emits them as an array when the source completes.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

interval(100)

.pipe(take(10), toArray())

.subscribe(console.log);

SCAN

It combines all values emitted on the source and joins them. The only difference between reduce and scan is it emits intermediate accumulations.

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

const clickEvent = fromEvent(document, 'click');
const observableOne = clickEvent.pipe(mapTo(1));
const seed = 0;
const data = observableOne.pipe(scan((acc, one) => acc + one, seed));
data.subscribe(val => console.log(val));

46. What is the difference between mergemap/switchmap/concatmap and exhaustmap and where we can use them?

I like one of the best answers from StackOverflow from ZahiC.

  • mergeMap — creates an Observable immediately for any source item, all previous Observables are kept alive

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

  • concatMap — waits for the previous Observable to complete before creating the next one

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

  • switchMap — for any source item, completes the previous Observable and immediately creates the next one

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

  • exhaustMap — source items are ignored while the previous Observable is not completed

https://rxjs-dev.firebaseapp.com/api/operators

https://rxjs-dev.firebaseapp.com/api/operators

To Understand more clearly let's check the below animation

if you have observed

  1. switchmap will return the outer observable only after the user finish typing so it will cancel all older observables once a new letter starts typing.

  2. concatmap will be called for each letter I type so outer observable calls each time user will type something so we can see a delay of 1 second for all typing letters

  3. mergemap will be called immediately still it will keep older observable alive.

  4. exhausmap will wait for one observable to finish before starting a new one so you can see outer observable might not have the latest value typed in the textbox.

you can check out some practical examples here.

https://stackblitz.com/edit/rxjs-map-diff

47. Discuss different decorators in Angular.

One of the main purposes of a decorator is storing metadata about a class, method, or property. The whole point of a decorator is to store metadata about a class, method, or property as we've already explored.

  • Class decorators: @Component, @NgModule, @Pipe

  • Property decorators for properties inside classes: @Input, @Output, @ContentChild, @ContentChildren, @ViewChild, @ViewChildren

  • Method decorators for methods inside classes: @HostListener, @HostBinding

  • Parameter decorators for parameters inside class constructors: @Inject

48. Explain different lifecycle methods in Angular.

  1. Constructor: A default method which is called when the class is instantiated.

  2. ngOnChanges: Executes when a new component is created, when one of the bound properties with @Input changes, also it is the only hook that takes an argument when it is called which is called as SimpleChanges.

  3. ngOnInit: Called once the component is initialized. This doesn't allow the component to be visible over the DOM. This runs just after the constructor.

  4. ngDoCheck: Runs when change detection runs. It also runs if there is no change and even if it is just an event that occurred, just in case to make sure if there is something that has changed. (For eg: It will run after a button click event irrespective of that it is making ant change or not).

  5. ngAfterContentInit: This is called after content(ng-content) has been projected into the view.

  6. ngAfterContentChecked: This is called after every projected content has been checked.

  7. ngAfterViewInit: Called after the components view (and child view) has been initialized.

  8. ngAfterViewChecked: Called every time the view (and child view) has been checked.

49. Explain the hierarchy of the Angular Life cycle hooks.

This Diagram given by Raed Khalaf helped me a lot to check the flow of the angular life cycle hooks.

Let's check out some practically how it works.

https://stackblitz.com/edit/lifecycle-hooks-angular

50. What is renderer 2?

Renderer2 is a simple default wrapper around DOM manipulation browser API. Renderer2 is primarily used by creating a Custom Directive.

constructor(el: ElementRef, renderer: Renderer2) {
    renderer.addClass(el.nativeElement, 'some');
}

you can check out practical examples here.

https://stackblitz.com/edit/renderer2-example-2

51. What is the difference between renderer and ElementRef?

I love the answer provided by Günter Zöchbauer from StackOverflow.

The Renderer is a class that is a partial abstraction over the DOM. Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break).

ElementRef is a class that can hold a reference to a DOM element. This is again an abstraction to not break in environments where the browsers DOM isn't actually available.

If ElementRef is injected to a component, the injected instance is a reference to the host element of the current component.

Renderer acts on the DOM and ElementRef is a reference to an element in the DOM the Renderer acts on.

52. What is Zone.js?

From one of the StackOverflow answered by ArunValaven

Zone creates a wrapper around all asynchronous operations in the browser such as user interactions, HTTP, timers, and any other changes that can cause changes in state.

Zone knows when any these operations completes. Angular in-turn, subscribes to notifications from Zone for whenever one of these operations completes. This lets Angular know that it can run its change detection algorithms and re-render anything that has changed.This minimizes any rendering churn and makes it efficient.

In some cases, we might want our code to be executed without a zone then we can use the method runOutsideAngular of the NgZone.

When we run outside zone none of the async events will be picked by Angular which means there is no Change Detection takes in place. This is means the view will not be updated until we re-enter the zone.

This feature can be helpful only when we don't want to update the view all time and want to update the view after a certain time.

Below is stackblitz to check practically:

https://stackblitz.com/edit/angular-zone-psplsu

53. What is Race Condition in Angular?

Race conditions mostly happen with the autocomplete features where the user is tying one input word ‘test' and API service call happens to get the data for ‘test and in between sudden user started typing the other characters ‘test' and API fetches the result first for ‘abc'… now the older service call for ‘test' finishes and give results of a test which might lead to data overwritten of the ‘abc'.

This type of situation happens when one observable gets delayed somehow and the other observable finishes first.

Solution:

To resolve this issue we need to cancel the older observable for ‘test' once the user started typing ‘abc'. RXJS provides a solution using switchmap to achieve this.

this.form
    .get('userInput')
    .valueChanges
    .pipe(
        debounceTime(500),
        tap(() => this.isLoading = true),
        switchMap(value => this.service.search({
                name: value
            }, 1)
            .pipe(
                finalize(() => this.isLoading = false),
            )
        )
    )
    .subscribe(response => this.data = response);

You can see practical examples here.

https://stackblitz.com/edit/angular-material-autocomplete-async2

54. What is a callback, Promises and Async/Await in Angular?

Callbacks: A callback is a function that is passed to another function. When the first function is done, it will run the second function.

function(callback){
  //do some tasks
   callback();
}

Promises: A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running without interruption. (source)

test(function(){
    return test1(function(){
        return test2(function(){
            return test3(function(){
                done()
            })
        })
    })
})

It makes it more readable like this:

test()
    .then(test1)
    .then(test2)
    .then(test3)
    .then(done)

Async / Await: The async function is used to write asynchronous code, specifically promises. inside of this function, the keyword await is used to pause the execution of a promise until it is resolved. In other words, it waits for the promise to resolve and then resume the async function.

async function test(){
    let data = await getData() // it waits until we get data
    return data;
}

55. What is Host binding and Host Listener in Angular?

@HostListener - will continuously listen to the event emitted by the host element which is declared with @HostListener.

@HostBinding - It will bind with the property to the host element, If anything happens to bind, HostBinding will update the host element.

In simple words,

  • @HostBinding: This decorator binds a class property to a property of the host element.

  • @HostListener: This decorator binds a class method to an event of the host element.

You can play with a practical example here.

https://stackblitz.com/edit/hostbinding-hostlistener

56. What is dependency injection in Angular?

Dependency Injection (DI) is a core concept of Angular and allows a class to receive dependencies from another class. Most of the time in Angular, dependency injection is done by injecting a service class into a component or module class.

In simple words,

A coding pattern in which a class receives the instances of objects it needs(called dependencies) from an external source rather than creating them itself.

You can check out practical examples here.

https://stackblitz.com/edit/angular-dependency-injection-services-example

57. Explain the digest cycle/Change detection Cycle in Angular.

In the newer version of the Angular digest cycle performed using the change detection cycle.

When the User change anything in the DOM following event occurs

  1. user updates DOM

  2. Angular uses zone to keep track of any async tasks ( clicks, setInterval, Service Requests)

  3. Angular detects changes

  4. change detection checks every component in the component tree from top to bottom to see if any model changes happened.

  • Angular component tree and change detector which is created during the application bootstrap process will be activated

  • the detector compares the current value with previous values

  • if the value is changed it will set isChanged to true.

  • note: this change detection is not a deep comparison.

  1. if there is new values the Component's view will be updated.

https://www.mokkapps.de/blog/the-last-guide-for-angular-change-detection-you-will-ever-need/

https://www.mokkapps.de/blog/the-last-guide-for-angular-change-detection-you-will-ever-need/

58. What is the difference between markForCheck and detectchanges?

cd.detectChanges() will run change detection right away from the current component down through its descendants.

cd.markForCheck() will not run change detection, but mark its ancestors as needing to run change detection. Next time any change detection happens, it will run also for those components which were marked.

  • If we want to reduce the number of times change detection is called use cd.markForCheck(). Often, changes affect multiple components, and somewhere change detection will be called.

  • If we are changing the state in a component with more ancestors than descendants you may get a performance increase by using detectChanges() since we aren't unnecessarily running change detection on the component's ancestors.

59. What are the ways to clone the object?

There are 3 ways to clone an object in Angular.

1. Native approach (deep copy)

One of the best and older way of cloning method is native deep cloning using the JSON.stringify

JSON.parse(JSON.stringify(object))

const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(),  // stringified
  undef: undefined,  // lost
  inf: Infinity,  // forced to 'null'
  re: /.*/,  // lost
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date);  // result of .toISOString()

2. Reliable cloning using a library (deep copy)

We can use the already available libraries such as

  • Lodash — cloneDeep; can be imported separately via the lodash.clonedeep module and is probably your best choice if you're not already using a library that provides a deep cloning function

    var objects = [{ 'a': 1 }, { 'b': 2 }];var deep = _.cloneDeep(objects);
    

3. ES6 (shallow copy)

ES6 offers two different ways to clone an object, one is Object.assign, and the other is spread, operator.

var data= {val: "string"};
var newdata= Object.assign({}, data);
var newdata3= {...data};  // Spread Operator

60. Explain how Angular application loads/Initialize.

Below are the steps which will be executed after ng serve.

  1. It starts with Angular.json where we have all configurations of Angular Project, it will check all paths and configurations and search for main.ts file.

  2. main.ts is the entry point of the application. It calls the bootstrap module and tells the builder to bootstrap the app.

  3. What is bootstrap in Angular? It will interact with the HTML of the webpage and serve the Data.

  4. Then we bootstrap an Angular application and we pass app.module.ts as an argument. In app.module.ts we tell Angular: “There is the app component which you should know when you try to start yourself”.

  5. And Angular now analyzes this app component, reading the setup we pass there and there is SELECTOR app-root.

  6. Now Angular knows all modules, components, and scripts.

  7. Now, Angular is enable to handle app-root in the index.html and knows rules for the SELECTOR.

  8. the app-root selector should insert the app components and load the app component.html

  9. This is how the Angular application starts.

(source: https://dev.to/casperns/how-angular-trigger-indexhtml-and-start-working-1l46)

61. How to detect non-primitive type data when an @Input() value changes in Angular?

You can check out this article for a detailed understanding.

https://javascript.plainenglish.io/how-to-detect-when-an-input-value-changes-in-angular-5872c77517fc

62. What are the different Encapsulation strategies in Angular?

  1. ViewEncapsulation.None: By using this method we are exposing our styles to outer components. (Note: we need to be sure to use proper selectors)

  2. ViewEncapsulation.Emulated: This is the default method that basically not expose the style if we override something and we can also use global styles.

  3. ViewEncapsulation.ShadowDom: This encapsulation strategy utilizes the Shadow DOM, so it renders a component with its own shadowRoot.

63. What is Shadow DOM in Angular?

Shadow DOM basically allows a group of DOM implementation to be hidden inside a single element (which is the basic idea of components) and encapsulates styles to the element.

Angular doesn't use shadow DOM (default) nor virtual DOM.

With encapsulation: ViewEncapsulation.Emulated (default) there is no shadow DOM because style encapsulation is only emulated.

encapsulation: ViewEncapsulation.Native enables shadow DOM on browsers that support it natively or it's again emulated when the web components polyfill is loaded.

Shadow DOM is also not targeting performance as virtual DOM is, but style encapsulation.

64. Explain different types of directives in Angular.

There are three kinds of directives in Angular:

  1. Components — directives with a template.

  2. Structural directives — change the DOM layout by adding and removing DOM elements. (*ngIf ,*ngFor)

  3. Attribute directives — change the appearance or behavior of an element, component, or another directive

    @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } }

and HTML can be

<p appHighlight>Highlight me!</p>

65. What is the best way to unsubscribe the observable?

If we don't' unsubscribe the observable it can lead to memory leaks in the Angular application.

There are several ways to unsubscribe observables.

  1. unsubscribe method

  2. aync pipe

  3. RXJS take operators

  4. RXJS first operator

  5. npm library such as (unsubscribe all, sub sink)

66. What is Angular language service?

The Angular Language Service provides code editors with a way to get completions, errors, hints, and navigation inside Angular templates. It works with external templates in separate HTML files, and also with in-line templates.

Language services include:

  • Completions lists

  • AOT Diagnostic messages

  • Quick info

  • Go to definition

(source: https://angular.io/guide/language-service)

67. Difference between Angular's canLoad and canActivate?

The CanLoad guard prevents the loading of the Lazy Loaded Module. This can be used when we don't want the user to navigate to any routes of the module and even don't want to load the module.

{
    path: 'test',
    loadChildren: 'app/test/test.module#TestModule',
    canLoad: [AuthGuardService]
},

The canActivate guard prevents unauthorized users to access the route. This guard doesn't prevent the module to load by itself.

{
      path: '',
      component: TestComponent,
      children: [
        {
          path: 'test-data',
          component: TestListComponent,
          canActivate: [ AuthGuardService ]
        }
      ]
    }

68. How to check if route changes in Angular?

We can subscribe to the router events in the component constructor. NavigationStart and NavigationEnd or any other events can be used to check the activity.

constructor(private router: Router) {
router.events.subscribe(
        (event) => {
            if (event instanceof NavigationStart)
                // startroute
            if (event instanceof NavigationEnd) {
                // end route
            }
        });
}

69. Explain different router events in Angular

  1. NavigationStart: Navigation starts.

  2. RouteConfigLoadStart: Before the router lazy loads a route configuration.

  3. RouteConfigLoadEnd: After a route has been lazy loaded.

  4. RoutesRecognized: When the router parses the URL and the routes are recognized.

  5. GuardsCheckStart: When the router begins the guards phase of routing.

  6. ChildActivationStart: When the router begins activating a route's children.

  7. ActivationStart: When the router begins activating a route.

  8. GuardsCheckEnd: When the router finishes the guards phase of routing successfully.

  9. ResolveStart: When the router begins the resolve phase of routing.

  10. ResolveEnd: When the router finishes the resolve phase of routing successfully.

  11. ChildActivationEnd: When the router finishes activating a route's children.

  12. ActivationEnd: When the router finishes activating a route.

  13. NavigationEnd: When navigation ends successfully.

  14. NavigationCancel: When navigation is canceled.

  15. NavigationError: When navigation fails due to an unexpected error.

  16. Scroll: When the user scrolls.

(source: https://angular.io/api/router/Event)

70. What are the manual ways to trigger change detection in Angular.

We can use the following methods to trigger change detection manually in Angular.

  • NgZone.run(callback) — It will evaluate the callback function inside the Angular zone. NgZone is an injectable service for executing work inside or outside of the Angular zone.

  • ApplicationRef.tick() — This will check the full component tree for change detection in Angular.

  • ChangeDetectorRef.detectChanges() — This will check only the component and its child views for change detection.

  1. Discuss different pipes in Angular.

  2. What are the best security practices you follow in Angular.

  3. What is the best way to improve Angular performance.

  4. Have you handled the expression has changed after it was checked error?

  5. What is the way to handle if one module is already loaded?

  6. Have you created a custom library in Angular?

  7. What are the ways you analyze the memory in Application?

  8. Explain different router events in Angular?

  9. What are the data types in Angular.

  10. What is the best way to optimize Async Validators?

  11. What is Enums in Angular?

  12. What is the difference between find and filter in JavaScript?

  13. Prevent Multiple Service Calls on Button Click in Angular.

  14. How to pass data between components in Angular?

  15. What is the difference between (change) vs (ngModelChange)?

  16. What is the difference between declarations, providers, and import ?

  17. How to Override CSS in Angular Component Libraries (such as Angular Material)?

  18. How to do dynamically bind string from component to HTML?

89.How to set ngFor and ngIf on the same element?

  1. Can you give an example of built-in validators?

  2. What is an entry component?

  3. What is observable and observer in Angular?

  4. What are service workers in Angular?

  5. How to update all libraries with the latest version in Angular?

  6. What is an interceptor? How you configured your application/

  7. Explain the architecture of your Angular Application.

  8. Explain some methods you mostly use to test the Angular Components.

  9. What are the different SCSS functions you used in your application.

  10. What is the difference between OnPush and default change detection?

  11. How can you bind data to templates?

  12. What is the difference between takeWhile and takeUntil RXJS Operator?

  13. What is the difference between BehaviourSubject/Subject/ReplaySubject and Async Subject?

  14. Explain practical usage of the ng-temple,ng-content,ng-container, and ng-templateOutlet.

  15. Why we use the forchild and forroot method in route? What is it's usage?

  16. How to update all Angular libraries to the latest versions?

  17. What is a content projection in Angular and How it works?

  18. What is the APP_INITILIZER in Angular and What it is used for?

  19. Explain route reuse strategies in Angular Application.

  20. How does Server-Side rendering work in Angular?

  21. What are service workers in Angular? How to use them?




Continue Learning