Enrichvia - Business Together To Make Investments

Top Angular Interview Questions and Answers for Junior / Senior / Lead level developers based on Interviewee’s experience

Event Capturing Vs Bubbling

Capturing – an event moves from the outermost element to the target

Bubbling – the event movement begins from the target to the outermost element in the file.

 

flatMap/mergeMap – creates an Observable immediately for any source item, all previous Observables are kept alive.

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

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

exhaustMap – while the previous Observable is not completed, source items are ignored

n summary, ViewChild is used to access child components or elements in the template, while @Input and @Output are used to pass data between components

 

Template forms vs Reactive Forms

1. FormsModule, ReactiveFormsModule

2. logic will in be in template, in component(typescript code)

3. asynchronus, synchronus

4a. We have seen both the ways to build forms in Angular. The template-driven approach would be familiar to those coming from AngularJS 1 background and thus makes it easy for migrating their app to the latest Angular version.

4b. The Reactive approach removes the core validation logic from the template and hence makes the template code quite clean. From a unit testing perspective, it is easier to write unit tests with Reactive forms, since the logic is contained inside our component.

5a. ngModel, form.errors,.dirty,.touched

5b. formGroup, formControl, Validators.required

 

rxjs

obserables – {

provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.

}

 

observer subscription subjects scheduler

operators:

Operators are functions. There are two kinds of operators: Pipeable and Creation

* A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified.

* Distinct from pipeable operators, creation operators are functions that can be used to create an Observable with some common predefined behavior or by joining other Observables.

 

Angular Map:

Map is an important function which is used to transform data as per our requirement. Suppose we are receiving some data (data can be received either from API or we can use an array value) and we do not want to use the same data but need to modify it before using it in our application.

 

Higher-order Observables

Observables most commonly emit ordinary values like strings and numbers, but surprisingly often, it is necessary to handle Observables of Observables, so-called higher-order Observables.

 

Creation Operators:

ajax

bindCallback

bindNodeCallback

defer

empty

from

fromEvent

fromEventPattern

generate

interval

of

range

throwError

timer

iif

 

Join Creation Operators

These are Observable creation operators that also have join functionality — emitting values of multiple source Observables.

 

combineLatest

concat

forkJoin

merge

partition

race

zip

Transformation Operators

buffer

bufferCount

bufferTime

bufferToggle

bufferWhen

concatMap

concatMapTo

exhaust

exhaustMap

expand

groupBy

map

mapTo

mergeMap

mergeMapTo

mergeScan

pairwise

partition

pluck

scan

switchScan

switchMap

switchMapTo

window

windowCount

windowTime

windowToggle

windowWhen

Filtering Operators

audit

auditTime

debounce

* Debouncing waits for a certain time before invoking the function again.

debounceTime

* debounceTime will emit a value from the source stream only if a given time has passed without source producing more values. throttleTime will start a timer when the source emits. It can be set to emit the first and/or the last value in the given time window.

distinct

distinctUntilChanged

distinctUntilKeyChanged

elementAt

filter

first

ignoreElements

last

sample

sampleTime

single

skip

skipLast

skipUntil

skipWhile

take

takeLast

takeUntil

takeWhile

throttle

* Throttling limits the number of times the function can be called over a certain period. Ensures that the function is called only once, even if the event is triggered multiple times.

 

throttleTime

Join Operators

Also see the Join Creation Operators section above.

 

combineLatestAll

concatAll

exhaustAll

mergeAll

switchAll

startWith

withLatestFrom

Multicasting Operators

multicast

publish

publishBehavior

publishLast

publishReplay

share

Error Handling Operators

catchError

retry

retryWhen

Utility Operators

tap

delay

delayWhen

dematerialize

materialize

observeOn

subscribeOn

timeInterval

timestamp

timeout

timeoutWith

toArray

Conditional and Boolean Operators

defaultIfEmpty

every

find

findIndex

isEmpty

Mathematical and Aggregate Operators

count

max

min

reduce

 

NgRx

MANAGE STATE

NgRx Store provides reactive state management for Angular apps inspired by Redux. Unify the events in your application and derive state using RxJS.

https://ngrx.io/generated/images/guide/store/state-management-lifecycle.png

 

@ngrx/store

Store is RxJS powered global state management for Angular applications, inspired by Redux. Store is a controlled state container designed to help write performant, consistent applications on top of Angular.

 

Key concepts

Actions describe unique events that are dispatched from components and services.

State changes are handled by pure functions called reducers that take the current state and the latest action to compute a new state.

Selectors are pure functions used to select, derive and compose pieces of state.

State is accessed with the Store, an observable of state and an observer of actions.

Local state management

NgRx Store is mainly for managing global state across an entire application. In cases where you need to manage temporary or local component state, consider using NgRx ComponentStore.

 

viewchild + contentchild =

While the ViewChild decorator allows to query for a single element from the view DOM, the ContentChildren decorator queries a list of elements in the content DOM

 

ViewEncapsulation

* ViewEncapsulation.None is simple no encapsulation

* ViewEncapsulation.Emulated (currently the default in Angular2) – adds attributes to component tags and child elements and manipulates the CSS (adding the attributes to the selectors) added to the page so the styles don’t bleed into each other – to keep styles scoped to the components where they are added even though the styles are all added collected in the head of the page when components are loaded.

* ViewEncapsulation.Native creates custom elements with shadow DOM where the browsers native implementation ensures the style scoping.

{

Native: Uses browser’s native Shadow DOM. Check for browser support before enabling it.

ShadowDom: Uses browser’s native Shadow DOM v1 for better cross-browser support and is a shared standard across the browsers. Check the difference between Shadow DOM v0 to v1.

Emulated: Imitates behavior of Shadow DOM to scope the CSS for component and appends to the head.

None: Neither Shadow DOM nor custom implementation, like global CSS which gets appended to the head

}

 

templateref, elementref, ViewEncapsulation

ElementRef is simply like document.getElementById(‘myId’); Using ElementRef you are only able to do some decorations

TemplateRef is an embedded template which you can use in ViewContainerRef.createEmbeddedView to create Embedded View.

*ngFor is doing the same, it reads the element as a TemplateRef and injects mutiple times to create view with data

TemplateRef cannot be used as an element for css decorations in .ts

 

lifecycle hooks – onchange, oninit, docheck, aftercontentinit, aftercontentchecked, afterviewinit, afterviewchecked, destroy

 

, DI,

 

routing –  routerLink, routerLinkActive

 

module, directive, pipes,

bootstrapping — The bootstrap property or key of the NgModule decorator specifies which component should be loaded by Angular when the app-level module loads

 

, library, aot, jit, latest version

 

unit testing

 

e2e

 

es6, event propagation, bubbling, capturing, closure, arrow, lexical scope, promises, pure/impure,

reduce – executes a reducer function for each array element | returns single value,

map, filter, inner functions

Lexical scoping refers to the variables in the location of a function’s definition, whereas dynamic scoping refers to the variables in the location of a function’s invocation.

 

Closure in JavaScript is a form of lexical scoping used to preserve variables from the outer scope of a function in the inner scope of a function. Lexical scoping is the process used to define the scope of a variable by its position in the source code.

https://stackoverflow.com/questions/111102/how-do-javascript-closures-work

coding – reverse array, remove duplicates, star, count repeated strings, prime or not, ===, null == Null

 

security tokens

 

–loading

 

10 JavaScript Naming Conventions Every Developer Should Know

https://www.syncfusion.com/blogs/post/top-javascript-naming-convention.aspx

Angular Promises Versus Observables

https://www.syncfusion.com/blogs/post/angular-promises-vs-observables.aspx

 

Latest – Angular 16 Unveiled: Discover the Top 7 Features

https://www.syncfusion.com/blogs/post/angular-16-top-7-features.aspx

 

1. Angular Signals

Angular Signals is the main feature developers have been waiting for since the Angular 16 roadmap was released. Although Solid.js inspired this concept, it is a whole new concept for Angular. It allows you to define reactive values and express dependencies between them. In other words, you can efficiently use Angular signals to manage state changes within Angular applications.

 

A signal can be recognized as a regular variable that users can synchronously access. But it comes with some additional features like notifying others (component templates, other signals, functions, etc.) of its value changes and creating a derived state in a declarative way.

 

The following example shows how to use Angular signals.

 

import { Component, computed, effect, signal } from ‘@angular/core’;

import { CommonModule } from ‘@angular/common’;

import { bootstrapApplication } from ‘@angular/platform-browser’;

 

@Component({

selector: ‘my-app’,

standalone: true,

imports: [CommonModule],

template: `

<h1>Calculate Area</h1>

<p>Answer : {{ area() }}</p>

<button (click)=”calculateArea(10,10)”>Click</button>

`,

})

 

export class App {

height = signal(5);

width = signal(5);

area = computed(() => this.height() * this.width());

constructor() {

effect(() => console.log(‘Value changed:’, this.area()));

}

calculateArea(height: number, width: number) {

this.height.set(height);

this.width.set(width);

}

}

In this example, I have created a computed value area and two signals named height and width. When the values of the signals are changed by invoking the calculateArea() function, the computed value will be updated and displayed in the template. Here is a working Stackblitz example for you to try it.

 

Although this looks fantastic, Angular has not abandoned zone.js and RxJS. Signals are an optional feature, and Angular will still work without them. Angular will gradually improve Signals in upcoming versions to make it a complete package.

 

Syncfusion Ad

Syncfusion Angular components are:

 

Lightweight

Modular

High-performing

Explore Now

2. Server-Side Rendering

The lack of server-side rendering (SSR) support was one of the most significant drawbacks of Angular compared to React. Angular 16 has resolved this issue with some significant improvements for server-side rendering.

 

Before, Angular used destructive hydration for SSR. In destructive hydration, the server first renders and loads the application to the browser. Then, when the client app gets downloaded and bootstrapped, it destroys the already rendered DOM and re-renders the client app from scratch. This approach caused significant UX issues, like screen flickering, and negatively impacted some Core Web Vitals such as LCP or CLS.anug.

 

Angular 16 introduces a new approach called non-destructive hydration to prevent these drawbacks. The DOM is not destroyed when the client app is downloaded and bootstrapped. It uses the same DOM while enriching it with client-side features like event listeners.

 

Non-destructive hydration is still at the developer preview stage. But you can enable it by adding provideClientHydration() as a provider when bootstrapping the application.

 

import {

bootstrapApplication,

provideClientHydration,

} from ‘@angular/platform-browser’;

 

 

bootstrapApplication(RootCmp, {

providers: [provideClientHydration()]

});

According to the official Angular release note, this is just the beginning. They plan to explore partial hydration as the next step and work on several developer requests. You can find more about the Angular SSR development plan here.

 

3. Experimental Jest Support

Jest is one of the most-used testing frameworks among JavaScript developers. Angular has listened to developer requests and has introduced experimental Jest support with Angular 16.

 

All you have to do is install Jest using npm and update the angular.json file.

 

// Install jest

npm install jest –save-dev

 

// angular.json

{

“projects”: {

“my-app”: {

“architect”: {

“test”: {

“builder”: “@angular-devkit/build-angular:jest”,

“options”: {

“tsConfig”: “tsconfig.spec.json”,

“polyfills”: [“zone.js”, “zone.js/testing”]

}

}

}

}

}

They plan to move all the existing Karma projects to Web Test Runner in future updates.

 

Syncfusion Ad

Each and every property of Syncfusion Angular components are completely documented for easy access.

 

Read Now

4. esbuild-Based Build System

Angular 16 introduces an esbuild-based build system for the development server (ng serve). Vite powers this new development server and uses esbuild to build artifacts.

 

This is still at the developer preview stage, but you can enable it by updating the angular.json file with the following.

 

“architect”: {

“build”: {

“builder”: “@angular-devkit/build-angular:browser-esbuild”,

5. Required Inputs

In Angular 16, you can now define input values as required. You can either use the @Input decorator or the @Component decorator inputs array to define one.

 

export class App {

@Input({ required: true }) name: string = ”;

}

 

// or

@Component({

inputs: [

{name: ‘name’, required: true}

]

})

6. Router Inputs

Angular 16 allows you to bind route parameters into component inputs, removing the need to inject ActivatedRoute into the components. To enable this feature, you must import RouterModule and enable the bindToComponentInputs property in the app.module.ts file.

 

@NgModule({

imports: [

RouterModule.forRoot([], {

bindToComponentInputs: true

})

],

})

export class AppModule {}

The following example shows how we can bind query params to component inputs.

 

// Route

const routes: Routes = [

{

path: “articles”,

component: ArticleComponent,

},

];

 

// Component

@Component({})

export class ArticleComponent implements OnInit {

 

@Input() articleId?: string;

 

ngOnInit() {

 

}

}

Now, when you navigate to the articles route, you can pass query params using the name of the component input. In this case, an example URL will look like the following.

 

http://localhost:4200/articles?articleId=001

If the input name is too long, you can rename the query parameter.

 

http://localhost:4200/articles?id=001

 

@Input(‘id’) articleId?: string;

You can also use this approach to bind path parameters and route data.

 

Syncfusion Ad

Be amazed exploring what kind of application you can develop using Syncfusion Angular components.

 

Try Now

7. Standalone Project Support

Angular 14 started supporting standalone components, which are independent of modules. Angular 16 takes this to the next level by supporting standalone project creation.

 

Angular 16 has a flag to create a standalone project through the Angular CLI. You have to execute ng new command with the –standalone flag. Then, it will generate a project without NgModules.

 

ng new –standalone

Standalone Project Support in Angular 16

 

Other Features

Angular 16 comes with many other changes that improve the developer experience:

 

Auto-importing of components and pipes through the language service.

Support for TypeScript 5.0, ECMAScript decorators, service workers, and SCP through the CLI.

CSP support for online styles.

Self-closing tags.

Cease of support for ngcc and TypeScript 4.8.

Conclusion

Overall, Angular 16 has delivered some significant features. Most of these features are stepping stones to much larger updates we can expect in the subsequent versions. You can follow Angular’s official documentation to upgrade your existing projects to Angular 16.

 

Syncfusion’s Angular UI component library is the only suite you will ever need to build an app. It contains over 75 high-performance, lightweight, modular, and responsive UI components in a single package.

 

What are Angular directives?

In Angular, Directives are defined as classes that can add new behavior to the elements in the template or modify existing behavior. The purpose of Directives in Angular is to maneuver the DOM, be it by adding new elements to DOM or removing elements and even changing the appearance of the DOM elements

 

How to call API in Angular?

To make an API call in Angular, we primarily use the HttpClient module. …

The most common type of API call in Angular is the GET request, which is used to retrieve data from the server. …

Just as we can retrieve data using a GET request, we can also send data to an API using a POST request.

 

angular.json

A file named angular. json at the root level of an Angular workspace provides workspace-wide and project-specific configuration defaults for build and development tools provided by the Angular CLI. Path values given in the configuration are relative to the root workspace folder.

 

package.json

In an Angular app, package. json is a file that contains information about the project and its dependencies. It is a part of the Node. js ecosystem and is used by the npm (Node Package Manager) to manage the packages required by the project.

 

tsconfig.json

The tsconfig.json file specifies the root files and the compiler options required to compile the project. JavaScript projects can use a jsconfig.json file instead, which acts almost the same but has some JavaScript-related compiler flags enabled by default.

 

event vs property binding

Event binding is the one-way data binding which sends the value from the view to the component which is in contrast to the property binding where we used to send the data from component to the view.02-Dec-2017

 

Pure and Impure Functions in JavaScript

 

JSReference

 

——-

codePart

use viewchild, input, output, directive, pipe, rxjs, promises,

[]==[] // false

Objects are not identical. In this case you compare the references to the objects. Easily speaking you compare the addresses in memory where these objects are located. This rule doesn’t relate to primitives where you compare the actual values.

 

 

var a = [],

b = [];

a == b; // false

a == a; // true

 

Multidimensional array to Single dimensional array – brute force approach

 

——————————————–

netSET

What is the difference between Promises and Observables?

https://stackoverflow.com/questions/37364973/what-is-the-difference-between-promises-and-observables?rq=1

Difference between Constructor and ngOnInit?

https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit?rq=1

Dynamically updating css in Angular 2

https://stackoverflow.com/questions/35882670/dynamically-updating-css-in-angular-2?rq=1

Property ‘…’ has no initializer and is not definitely assigned in the constructor

https://stackoverflow.com/questions/49699067/property-has-no-initializer-and-is-not-definitely-assigned-in-the-construc?rq=1

What is the difference between BehaviorSubject and Observable?

https://stackoverflow.com/questions/39494058/what-is-the-difference-between-behaviorsubject-and-observable?rq=1

get and set in TypeScript

https://stackoverflow.com/questions/12827266/get-and-set-in-typescript?rq=1

access key and value of object using *ngFor

https://stackoverflow.com/questions/35534959/access-key-and-value-of-object-using-ngfor?rq=1

You could create a custom pipe to return the list of key for each element. Somethin

 

 

https://medium.com/@rahul.a1739/router-improvements-and-lazy-loading-in-angular-17-a-detailed-tutorial-55e3b7c988ef

 

https://medium.com/@rahul.a1739/standalone-components-in-angular-17-a-detailed-tutorial-0bf17955fc70

 

https://medium.com/@rahul.a1739/signals-and-effects-in-angular-a-detailed-tutorial-8a18e0878493

 

https://medium.com/@kolheankita15/top-10-angular-interview-questions-2bf9866ab65b

 

https://medium.com/@info_65725/state-management-in-angular-ngrx-vs-akita-e31d81a2ec87

 

https://blog.techvibes.io/my-3-favorite-angular-17-features-ad7e05bd360b

 

https://medium.com/@rahul.a1739/ngrx-interview-questions-2ab5e0851444

 

https://www.javastructures.com/misc/ngrx

 

https://www.geeksforgeeks.org/async-await-function-in-javascript/?ref=ml_lbp

 

https://aw.club/global/en/blog/senior-angular-developer-interview-questions

 

By Enrichvia WebTeam

Jobs & Education Portal

Leave a Reply

Your email address will not be published. Required fields are marked *