Angular Interview Questions for Freshers and Experienced Developers
Full Stack Developer Interview Questions -
Angular interview questions for fresher and experienced developer
1. Difference between Angular 2, 6, 7, 8, 9, 10
- Angular 2: Introduction of the complete rewrite with TypeScript, faster change detection, and dependency injection.
- Angular 6: Addition of Angular Elements, Service Worker, CLI prompts, Tree Shakable Providers.
- Angular 7: Improved CLI, virtual scrolling, drag and drop.
- Angular 8: Differential loading for better performance, support for dynamic imports, and Ivy preview.
- Angular 9: Ivy becomes the default compiler, improved testing and smaller bundles.
- Angular 10: Smaller updates, strict mode, TypeScript 3.9 support, and better error messages.
- Angular 2: Introduction of the complete rewrite with TypeScript, faster change detection, and dependency injection.
- Angular 6: Addition of Angular Elements, Service Worker, CLI prompts, Tree Shakable Providers.
- Angular 7: Improved CLI, virtual scrolling, drag and drop.
- Angular 8: Differential loading for better performance, support for dynamic imports, and Ivy preview.
- Angular 9: Ivy becomes the default compiler, improved testing and smaller bundles.
- Angular 10: Smaller updates, strict mode, TypeScript 3.9 support, and better error messages.
2. Subjects in RxJS
- Subject: Multicast Observable, allows multiple subscribers.
- BehaviorSubject: Has a default value, and subscribers get the latest emitted value.
- ReplaySubject: Replays the last few emissions to new subscribers.
- AsyncSubject: Emits only the last value when the Observable completes.
import { Subject } from 'rxjs';
let subject = new Subject();
subject.subscribe(value => console.log('Subscriber 1:', value));
subject.next(1);
- Subject: Multicast Observable, allows multiple subscribers.
- BehaviorSubject: Has a default value, and subscribers get the latest emitted value.
- ReplaySubject: Replays the last few emissions to new subscribers.
- AsyncSubject: Emits only the last value when the Observable completes.
3. RxJS
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables.
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables.
4. Publisher-Subscriber Model in Angular
Angular uses the publisher-subscriber pattern through Observables for asynchronous data streams. Components can subscribe to services that publish data.
@Injectable({ providedIn: 'root' })
export class DataService {
private dataSubject = new BehaviorSubject<string>('default');
data$ = this.dataSubject.asObservable(); updateData(newData: string) {
this.dataSubject.next(newData);
}
}
Angular uses the publisher-subscriber pattern through Observables for asynchronous data streams. Components can subscribe to services that publish data.
private dataSubject = new BehaviorSubject<string>('default');
data$ = this.dataSubject.asObservable();
this.dataSubject.next(newData);
}
}
5. CLI Commands
ng new
: Create a new Angular application.ng serve
: Start a local development server.ng build
: Build the application.ng test
: Run tests.
ng new
: Create a new Angular application.ng serve
: Start a local development server.ng build
: Build the application.ng test
: Run tests.
6. Angular Application Workflow
- Component Creation: Angular components render UI.
- Module Management: Each app has an
AppModule
. - Services: Used to share data and logic.
- Routing: Manages navigation between views.
- Component Creation: Angular components render UI.
- Module Management: Each app has an
AppModule
. - Services: Used to share data and logic.
- Routing: Manages navigation between views.
7. Transpiling
Transpiling converts TypeScript to JavaScript. Angular uses TypeScript which is transpiled to JavaScript to run in the browser.
Transpiling converts TypeScript to JavaScript. Angular uses TypeScript which is transpiled to JavaScript to run in the browser.
8. AOT (Ahead of Time Compilation)
AOT compiles the app during the build time for better performance and smaller bundle sizes.
AOT compiles the app during the build time for better performance and smaller bundle sizes.
9. Data Passing in Angular
- @Input(): Pass data from parent to child.
- @Output(): Emit data from child to parent.
- Services: Pass data between non-related components.
- @Input(): Pass data from parent to child.
- @Output(): Emit data from child to parent.
- Services: Pass data between non-related components.
10. Ivy
Angular’s Ivy renderer allows faster compilation, smaller bundles, and improved debugging.
Angular’s Ivy renderer allows faster compilation, smaller bundles, and improved debugging.
11. Interceptors
Angular HTTP interceptors allow you to modify requests or responses globally.
@Injectable()
export class AuthInterceptor implements HttpInterceptor
{
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
{
const clonedRequest = req.clone({ setHeaders: { Authorization: `Bearer token` } });
return next.handle(clonedRequest);
}
}
Angular HTTP interceptors allow you to modify requests or responses globally.
@Injectable()
export class AuthInterceptor implements HttpInterceptor
{
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
{
const clonedRequest = req.clone({ setHeaders: { Authorization: `Bearer token` } });
return next.handle(clonedRequest);
}
}
12. Resolver
Used to fetch data before navigating to a route.
@Injectable({ providedIn: 'root' })
export class DataResolver implements Resolve<any>
{
constructor(private dataService: DataService) {}
resolve(): Observable<any>
{
return this.dataService.getData();
}
}
Used to fetch data before navigating to a route.
export class DataResolver implements Resolve<any>
{
constructor(private dataService: DataService) {}
resolve(): Observable<any>
{
return this.dataService.getData();
}
}
13. Services & Data Transfer
Services in Angular allow sharing data between components.
@Injectable({ providedIn: 'root' })
export class DataService {
private data = new Subject<string>();
data$ = this.data.asObservable();
setData(newData: string) {
this.data.next(newData);
}
}
Services in Angular allow sharing data between components.
@Injectable({ providedIn: 'root' })
export class DataService {
private data = new Subject<string>();
data$ = this.data.asObservable();
setData(newData: string) {
this.data.next(newData);
}
}
14. Fetching and Filtering Data
- Fetching from JSON:
- Fetching from JSON:
this.http.get('url').subscribe(data => this.data = data);
- Filtering an array of objects:
- Filtering an array of objects:
let filtered = data.filter(item => item.id > 10);
15. ngFor and ngIf
*ngFor
is used to iterate over arrays.*ngIf
conditionally displays elements.
<div *ngFor="let item of items">{{ item }}</div> <div *ngIf="isVisible">Visible</div>
*ngFor
is used to iterate over arrays.*ngIf
conditionally displays elements.
16. Select in HTML
Binding select options:
<select [(ngModel)]="selectedValue"> <option *ngFor="let option of options" [value]="option.value">{{ option.name }}</option> </select>
Binding select options:
<select [(ngModel)]="selectedValue">17. Attribute Binding
Bind attributes dynamically:
Bind attributes dynamically:
18. Routing
Angular’s routing allows navigation between different views.
Angular’s routing allows navigation between different views.
19. Lifecycle Hooks
Lifecycle hooks manage component behavior at different stages. Example:
ngOnInit
: Called once the component is initialized.ngOnDestroy
: Cleanup logic.
Lifecycle hooks manage component behavior at different stages. Example:
ngOnInit
: Called once the component is initialized.ngOnDestroy
: Cleanup logic.
20. Pipes
Pipes are used to transform data in templates.
Pipes are used to transform data in templates.
21. Types of Directives
- Structural:
*ngIf
, *ngFor
. - Attribute:
[ngClass]
, [ngStyle]
.
- Structural:
*ngIf
,*ngFor
. - Attribute:
[ngClass]
,[ngStyle]
.
22. Two-Way Binding
Combine property and event binding:
Combine property and event binding:
23. @Input and @Output
- @Input(): Pass data from parent to child.
- @Output(): Emit events from child to parent.
- @Input(): Pass data from parent to child.
- @Output(): Emit events from child to parent.
24. CRUD in Angular
Example of basic CRUD operations:
Example of basic CRUD operations:
25. JavaScript Hoisting
Hoisting refers to the process where function and variable declarations are moved to the top of their scope.
Hoisting refers to the process where function and variable declarations are moved to the top of their scope.
26. Closures
A closure is a function that retains access to its parent scope even after the parent function has closed.
27. View Encapsulation in Angular
Angular offers three types of view encapsulation to control the CSS scope:
- Emulated (default): Angular adds unique attributes to elements to scope CSS locally.
- None: No encapsulation, meaning the styles are globally applied.
- Shadow DOM: Uses native Shadow DOM to completely isolate styles.
Example:
A closure is a function that retains access to its parent scope even after the parent function has closed.
27. View Encapsulation in Angular
Angular offers three types of view encapsulation to control the CSS scope:
- Emulated (default): Angular adds unique attributes to elements to scope CSS locally.
- None: No encapsulation, meaning the styles are globally applied.
- Shadow DOM: Uses native Shadow DOM to completely isolate styles.
Example:
28. Box Model
The CSS box model is how web elements are rendered. It includes:
- Content: The actual content.
- Padding: Space between the content and the border.
- Border: The border around the padding.
- Margin: Space outside the border.
Example:
The CSS box model is how web elements are rendered. It includes:
- Content: The actual content.
- Padding: Space between the content and the border.
- Border: The border around the padding.
- Margin: Space outside the border.
Example:
29. Lifecycle Hooks (Practical Usage)
Angular lifecycle hooks allow you to tap into key moments in a component's lifecycle.
ngOnInit
: Fetch data after component is initialized.ngOnChanges
: Respond to input property changes.ngOnDestroy
: Cleanup before the component is destroyed.
Example:
Angular lifecycle hooks allow you to tap into key moments in a component's lifecycle.
ngOnInit
: Fetch data after component is initialized.ngOnChanges
: Respond to input property changes.ngOnDestroy
: Cleanup before the component is destroyed.
Example:
30. Passing Data Between Siblings
To pass data between sibling components, use a shared service that holds the data, and inject it into both components.
Example:
- In sibling component A:
- In sibling component B:
To pass data between sibling components, use a shared service that holds the data, and inject it into both components.
Example:
- In sibling component A:
- In sibling component B:
31. Cloning Objects in JavaScript
You can clone an object using Object.assign()
or the spread operator.
Example:
You can clone an object using Object.assign()
or the spread operator.
Example:
32. Adding a Class Dynamically in JavaScript
Use classList.add()
to dynamically add a class to an element.
Example:
Use classList.add()
to dynamically add a class to an element.
Example:
33. Shadow Box in Angular
You can create shadow effects using CSS box-shadow
.
Example:
Example in Angular component:
You can create shadow effects using CSS box-shadow
.
Example:
Example in Angular component:
34. ViewChild and ViewChildren
- ViewChild: Access a single DOM element or component instance.
- ViewChildren: Access multiple elements or component instances.
Example:
- ViewChild: Access a single DOM element or component instance.
- ViewChildren: Access multiple elements or component instances.
Example:
35. SwitchMap
switchMap
cancels the previous observable when a new one is emitted.
Example:
switchMap
cancels the previous observable when a new one is emitted.
Example:
36. HostListener
Used to listen to DOM events in a directive or component.
Example:
Used to listen to DOM events in a directive or component.
Example:
37. ESLint
ESLint is a JavaScript linter that helps in finding and fixing problems in JavaScript and TypeScript code.
Example: ESLint rules can be configured in the .eslintrc.json
file.
ESLint is a JavaScript linter that helps in finding and fixing problems in JavaScript and TypeScript code.
Example: ESLint rules can be configured in the .eslintrc.json
file.
38. Event Loop
JavaScript’s event loop allows asynchronous code execution by pushing callbacks into the task queue and processing them after the current execution stack is empty.
JavaScript’s event loop allows asynchronous code execution by pushing callbacks into the task queue and processing them after the current execution stack is empty.
39. Callback Function
A function passed as an argument to another function that is executed after some operation is completed.
Example:
A function passed as an argument to another function that is executed after some operation is completed.
Example:
40. Package.json and Package-lock.json
- package.json: Contains metadata about the project and lists its dependencies.
- package-lock.json: Locks down the exact version of the dependencies installed in
node_modules
, ensuring consistent builds.
- package.json: Contains metadata about the project and lists its dependencies.
- package-lock.json: Locks down the exact version of the dependencies installed in
node_modules
, ensuring consistent builds.
Differences between major angular versions :
Angular 2
- Released: 2016
- Key Features:
- Complete rewrite of AngularJS (Angular 1).
- Introduced TypeScript, components-based architecture, better modularity.
- Dependency Injection improved.
- Change detection made faster and more efficient.
- Concept of services and Observables via RxJS for asynchronous programming introduced.
- Mobile-first approach.
- Released: 2016
- Key Features:
- Complete rewrite of AngularJS (Angular 1).
- Introduced TypeScript, components-based architecture, better modularity.
- Dependency Injection improved.
- Change detection made faster and more efficient.
- Concept of services and Observables via RxJS for asynchronous programming introduced.
- Mobile-first approach.
Angular 4 (No Angular 3, skipped to align versioning with Angular CLI)
- Released: 2017
- Key Features:
- Smaller and faster compared to Angular 2.
- Angular Universal support for server-side rendering (SSR).
- Animation package moved to a separate package (
@angular/animations
). - Improved
ngIf
and ngFor
directives with else
condition. - TypeScript 2.1 and 2.2 compatibility.
- Released: 2017
- Key Features:
- Smaller and faster compared to Angular 2.
- Angular Universal support for server-side rendering (SSR).
- Animation package moved to a separate package (
@angular/animations
). - Improved
ngIf
andngFor
directives withelse
condition. - TypeScript 2.1 and 2.2 compatibility.
Angular 5
- Released: Late 2017
- Key Features:
- Build optimizer introduced for better production builds.
HttpClient
introduced as a replacement for the Http
module.- Internationalization (i18n) improvements.
- Progressive Web App (PWA) support with Service Worker.
- Better handling of null values in templates.
- Released: Late 2017
- Key Features:
- Build optimizer introduced for better production builds.
HttpClient
introduced as a replacement for theHttp
module.- Internationalization (i18n) improvements.
- Progressive Web App (PWA) support with Service Worker.
- Better handling of null values in templates.
Angular 6
- Released: 2018
- Key Features:
- Angular Elements: Convert Angular components into custom elements (web components).
- Service Worker improvements for better PWA support.
- Tree Shakable Providers to reduce bundle sizes.
ng update
and ng add
CLI commands introduced for easier dependency management.RxJS 6
introduced with pipeable operators
.- Bazel build tool integration introduced for faster builds.
- Released: 2018
- Key Features:
- Angular Elements: Convert Angular components into custom elements (web components).
- Service Worker improvements for better PWA support.
- Tree Shakable Providers to reduce bundle sizes.
ng update
andng add
CLI commands introduced for easier dependency management.RxJS 6
introduced withpipeable operators
.- Bazel build tool integration introduced for faster builds.
Angular 7
- Released: Late 2018
- Key Features:
- CLI Prompts to guide users when generating components, services, etc.
- Virtual Scrolling and Drag-and-Drop features added to
@angular/cdk
. - Performance improvements with faster CLI builds.
- Dependency updates including support for TypeScript 3.1, RxJS 6.3.
- Improved error handling for templating issues.
- Released: Late 2018
- Key Features:
- CLI Prompts to guide users when generating components, services, etc.
- Virtual Scrolling and Drag-and-Drop features added to
@angular/cdk
. - Performance improvements with faster CLI builds.
- Dependency updates including support for TypeScript 3.1, RxJS 6.3.
- Improved error handling for templating issues.
Angular 8
- Released: Mid-2019
- Key Features:
- Differential loading: Serving different bundles for modern browsers and legacy browsers.
- Dynamic imports for lazy-loaded modules.
- Ivy engine introduced as an opt-in preview (smaller, faster compilations).
- Support for TypeScript 3.4.
- Web Worker support for offloading complex computations.
- Released: Mid-2019
- Key Features:
- Differential loading: Serving different bundles for modern browsers and legacy browsers.
- Dynamic imports for lazy-loaded modules.
- Ivy engine introduced as an opt-in preview (smaller, faster compilations).
- Support for TypeScript 3.4.
- Web Worker support for offloading complex computations.
Angular 9
- Released: Early 2020
- Key Features:
- Ivy as default: Ivy compiler and runtime become default, resulting in smaller bundle sizes and improved debugging.
- Improved testing, faster build times.
- AOT (Ahead-of-Time) compilation by default.
- Better internationalization support with improved locale-based support.
- Improved diagnostics and error messages.
- Released: Early 2020
- Key Features:
- Ivy as default: Ivy compiler and runtime become default, resulting in smaller bundle sizes and improved debugging.
- Improved testing, faster build times.
- AOT (Ahead-of-Time) compilation by default.
- Better internationalization support with improved locale-based support.
- Improved diagnostics and error messages.
Angular 10
- Released: Mid-2020
- Key Features:
- TypeScript 3.9 support.
- New strict mode for better error detection, smaller bundles, and improved performance.
- Deprecation of some old modules.
- Automatic handling of large dependencies via
ngcc
. - Improved performance by limiting the size of the default bundle.
- Released: Mid-2020
- Key Features:
- TypeScript 3.9 support.
- New strict mode for better error detection, smaller bundles, and improved performance.
- Deprecation of some old modules.
- Automatic handling of large dependencies via
ngcc
. - Improved performance by limiting the size of the default bundle.
Angular 11
- Released: Late 2020
- Key Features:
- Faster builds: Improvements to the build and compile speed.
- Improved Hot Module Replacement (HMR) for better development experience.
- Experimental support for Webpack 5.
- Component harnesses introduced in
@angular/cdk
for easier testing. - Linting changes: TSLint deprecated in favor of ESLint.
- Released: Late 2020
- Key Features:
- Faster builds: Improvements to the build and compile speed.
- Improved Hot Module Replacement (HMR) for better development experience.
- Experimental support for Webpack 5.
- Component harnesses introduced in
@angular/cdk
for easier testing. - Linting changes: TSLint deprecated in favor of ESLint.
Angular 12
- Released: Mid-2021
- Key Features:
- ESLint: TSLint fully removed in favor of ESLint.
- Nullish Coalescing Operator (
??
) support in templates. - Ivy Everywhere: The view engine is deprecated, Ivy is used in libraries.
- Strict typing improvements.
- Webpack 5 support enabled by default.
- Inline Sass support.
- Released: Mid-2021
- Key Features:
- ESLint: TSLint fully removed in favor of ESLint.
- Nullish Coalescing Operator (
??
) support in templates. - Ivy Everywhere: The view engine is deprecated, Ivy is used in libraries.
- Strict typing improvements.
- Webpack 5 support enabled by default.
- Inline Sass support.
Angular 13
- Released: Late 2021
- Key Features:
- No more support for IE11 (huge performance improvement).
- Dynamic Component Creation simplified.
- View Engine fully removed, Ivy is now the only rendering engine.
- Improvements in Router and testing tools.
- Updated Forms Module for better form control API handling.
- Improved accessibility support for Angular Material.
- Released: Late 2021
- Key Features:
- No more support for IE11 (huge performance improvement).
- Dynamic Component Creation simplified.
- View Engine fully removed, Ivy is now the only rendering engine.
- Improvements in Router and testing tools.
- Updated Forms Module for better form control API handling.
- Improved accessibility support for Angular Material.
Angular 14
- Released: Mid-2022
- Key Features:
- Standalone Components: Reduces the need for NgModules.
- Typed reactive forms: FormControl can now infer type.
- Streamlined page title management using router configuration.
- Built-in support for CLI autocompletion.
- Improved error messages for developers.
- Released: Mid-2022
- Key Features:
- Standalone Components: Reduces the need for NgModules.
- Typed reactive forms: FormControl can now infer type.
- Streamlined page title management using router configuration.
- Built-in support for CLI autocompletion.
- Improved error messages for developers.
Angular 15
- Released: Late 2022
- Key Features:
- Standalone APIs: Angular goes further with modularity by enhancing standalone components.
- Directive Composition API: Allows combining directives without needing wrappers.
- Zone.js-less Applications: Experimental support for applications that don't use
Zone.js
. - Improved performance with stable
ESM build outputs
. - New router features like bindToComponentInput, which enables direct bindings from router data to component inputs.
- Released: Late 2022
- Key Features:
- Standalone APIs: Angular goes further with modularity by enhancing standalone components.
- Directive Composition API: Allows combining directives without needing wrappers.
- Zone.js-less Applications: Experimental support for applications that don't use
Zone.js
. - Improved performance with stable
ESM build outputs
. - New router features like bindToComponentInput, which enables direct bindings from router data to component inputs.
Angular 16
- Released: Mid-2023
- Key Features:
- Signals: Reactive primitive introduced to handle state changes outside the component class.
- Hydration support: Improved for server-side rendering.
- Zone-less Angular: Improved support for applications without
Zone.js
, making them more performant. - Better DevTools Integration: Improved diagnostics and debugging.
- Reactivity system revamp: Angular's reactivity model gets more sophisticated with improved fine-grained change detection.
- Built-in
@angular/jest
support.
- Released: Mid-2023
- Key Features:
- Signals: Reactive primitive introduced to handle state changes outside the component class.
- Hydration support: Improved for server-side rendering.
- Zone-less Angular: Improved support for applications without
Zone.js
, making them more performant. - Better DevTools Integration: Improved diagnostics and debugging.
- Reactivity system revamp: Angular's reactivity model gets more sophisticated with improved fine-grained change detection.
- Built-in
@angular/jest
support.
Comments
Post a Comment