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.

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);

3. RxJS

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);
    }
}

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.

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.

7. Transpiling

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.

ng build --aot

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.

10. Ivy

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);

}

}

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();
}
}

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);

}

}

14. Fetching and Filtering Data

  • Fetching from JSON:

this.http.get('url').subscribe(data => this.data = data);

  • 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>

16. Select in HTML

Binding select options:

<select [(ngModel)]="selectedValue">
 <option *ngFor="let option of options" [value]="option.value">{{ option.name }}</option> </select>

17. Attribute Binding

Bind attributes dynamically:

<img [src]="imageUrl" [alt]="imageAlt">

18. Routing

Angular’s routing allows navigation between different views.

const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent } ];

19. Lifecycle Hooks

Lifecycle hooks manage component behavior at different stages. Example:

  • ngOnInit: Called once the component is initialized.
  • ngOnDestroy: Cleanup logic.
ngOnInit() { console.log('Component initialized'); }

20. Pipes

Pipes are used to transform data in templates.

<p>{{ price | currency }}</p>

21. Types of Directives

  • Structural*ngIf*ngFor.
  • Attribute[ngClass][ngStyle].

22. Two-Way Binding

Combine property and event binding:

<input [(ngModel)]="name">

23. @Input and @Output

  • @Input(): Pass data from parent to child.
  • @Output(): Emit events from child to parent.
@Input() message: string;
@Output() messageEvent = new EventEmitter<string>();

24. CRUD in Angular

Example of basic CRUD operations:

typescript
this.http.post('url', data).subscribe(response => console.log(response));

25. JavaScript Hoisting

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.

function outer() { let counter = 0; return function() { counter++; return counter; }; }

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:

@Component({
selector: 'app-example',
template: '<p>Example works!</p>',
styles: ['p { color: red; }'],
encapsulation: ViewEncapsulation.Emulated
})
export class ExampleComponent {}

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:

.box {
width: 200px;
padding: 10px;
border: 5px solid black;
margin: 20px;
}

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:

ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Cleanup on destroy');
}

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:


@Injectable({ providedIn: 'root' })
export class SharedService {
private dataSubject = new Subject<string>();
data$ = this.dataSubject.asObservable();
updateData(data: string) {
this.dataSubject.next(data);
}
}
  • In sibling component A:
    this.sharedService.updateData('new data');
  • In sibling component B:
    this.sharedService.data$.subscribe(data => console.log(data));

31. Cloning Objects in JavaScript

You can clone an object using Object.assign() or the spread operator.

Example:

const obj = { a: 1, b: 2 };
const cloneObj = { ...obj }; // Shallow clone

32. Adding a Class Dynamically in JavaScript

Use classList.add() to dynamically add a class to an element.

Example:

const element = document.getElementById('myElement');
element.classList.add('myClass');

33. Shadow Box in Angular

You can create shadow effects using CSS box-shadow.

Example:

.shadow-box {
box-shadow: 10px 10px 5px grey;
}

Example in Angular component:

@Component({
selector: 'app-shadow-box',
template: '<div class="shadow-box">Content</div>',
styles: ['.shadow-box { box-shadow: 10px 10px 5px grey; }']
})
export class ShadowBoxComponent {}

34. ViewChild and ViewChildren

  • ViewChild: Access a single DOM element or component instance.
  • ViewChildren: Access multiple elements or component instances.

Example:

@ViewChild('myElement') elementRef: ElementRef;
@ViewChildren('myElements') elements: QueryList<ElementRef>;
ngAfterViewInit() {
console.log(this.elementRef.nativeElement); // Single element
this.elements.forEach(el => console.log(el.nativeElement)); // Multiple elements
}

35. SwitchMap

switchMap cancels the previous observable when a new one is emitted.

Example:

searchTerms.pipe(
switchMap(term => this.searchService.search(term))
).subscribe(results => console.log(results));

36. HostListener

Used to listen to DOM events in a directive or component.

Example:

@HostListener('window:scroll', ['$event']) onScroll(event: Event) { console.log('Scroll event', event); }

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.

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.

39. Callback Function

A function passed as an argument to another function that is executed after some operation is completed.

Example:

function fetchData(callback) {
setTimeout(() => {
callback('data received');
}, 1000);
}

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

Comments

Popular posts from this blog

Border Radius not working in Outlook Email template

C# .Net Core Interview Questions for Freshers and Experienced Developers

15 ways to keep your team motivated while working remotely ?